需要使用纯Ruby的类

时间:2016-11-24 18:42:08

标签: ruby require

我遇到以下问题:

我想要一个" config / 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>'

1 个答案:

答案 0 :(得分:4)

  

要求'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'