【问题标题】:Require class with pure Ruby要求使用纯 Ruby 的类
【发布时间】:2016-11-24 18:42:07
【问题描述】:

我遇到了以下问题:

我想在我的 index.rb 中添加一个“config/application.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>'

【问题讨论】:

  • 试试require './config/application'

标签: ruby require


【解决方案1】:

需要“配置/应用程序”

在 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'

【讨论】:

  • 为清楚起见,最好使用$LOAD_PATH 而不是神秘的$:,这是一个很难在Google 上搜索到的符号。
  • @tadman 同意,但我将它们都放在答案中,因为人们很可能会在野外看到它们。 :) 感谢您的评论!争取可读性而不是聪明总是一个好主意。
  • 请注意,requireing 相对于当前工作目录的文件至少 非常 脆弱并且可能 非常 危险,因为当前工作目录不在您的控制范围内。这就是为什么 . 几十年来都不是 Unix 默认搜索路径的一部分,并且在 1.9 中已从 $LOAD_PATH 中删除。 始终使用与当前文件相关的require_relative,该文件在您的控制之下。
猜你喜欢
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 2012-12-16
  • 2023-03-28
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多