2016-11-24 24 views
0

我有以下問題:要求類純Ruby

我想需要「配置/ application.rb中」文件到我的index.rb

在我的任務中,我必須使用純Ruby。

配置/應用

Dir["app/models/*.rb"].each do |file| 
    require_relative file 
end 

Dir["app/importers/*.rb"].each do |file| 
    require_relative file 
end 

index.rb

require 'config/application' 

contas_endereco = ARGV[0].to_s 
transacoes_endereco = ARGV[1].to_s 

conta_arquivo = Arquivo.new(contas_endereco) 
transacoes_arquivo = Arquivo.new(transacoes_endereco) 

transacoes_importer = TransacoesImporter.new(conta_arquivo, transacoes_arquivo) 
transacoes_importer.importar 

但我得到這個錯誤:

/home/kelvin/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- config/application (LoadError) 
    from /home/kelvin/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' 
    from index.rb:1:in `<main>' 

我試圖require_relative過使用,但我得到了以下錯誤:

/home/kelvin/workspace-ruby/desafio-dinda/config/application.rb:2:in `require_relative': cannot load such file -- /home/kelvin/workspace-ruby/desafio-dinda/config/app/models/transacao.rb (LoadError) 
    from /home/kelvin/workspace-ruby/desafio-dinda/config/application.rb:2:in `block in <top (required)>' 
    from /home/kelvin/workspace-ruby/desafio-dinda/config/application.rb:1:in `each' 
    from /home/kelvin/workspace-ruby/desafio-dinda/config/application.rb:1:in `<top (required)>' 
    from index.rb:1:in `require_relative' 
    from index.rb:1:in `<main>' 
+2

嘗試'需要」 /配置/ application'' –

回答

4

require 'config/application'

在Ruby中,包含的文件與Kernel#require通常必須在$ LOAD_PATH或相對路徑給出,不包括文件擴展名。一些示例包括:

  • 將腳本的目錄添加到您的$ LOAD_PATH中。

    $:.unshift File.dirname(__FILE__) 
    require 'config/application' 
    
  • 要求相對於當前工作目錄的文件。

    require './config/application' 
    

您也可以使用Kernel#load絕對路徑。例如:

load '/path/to/config/application.rb' 
+1

爲清楚起見,最好使用'$ LOAD_PATH'神祕'$,而不是:',符號很難搜索在谷歌。 – tadman

+1

@tadman同意,但我把它們都放在答案中,因爲人們很可能在野外看到這兩者。 :)感謝您的評論!爲智能的可讀性而鬥爭永遠是一個好主意。 –

+0

請注意,由於當前工作目錄不在您的控制範圍之內,所以'要求相對於當前工作目錄的文件至少非常脆弱並且可能非常危險。這就是爲什麼'.'不是Unix幾十年來默認搜索路徑的一部分,並且已經從1.9中的$ LOAD_PATH中移除的原因。 *總是*使用'require_relative',這是相對於當前*文件*,* * *在您的控制之下。 –