Kelvin Matheus
Kelvin Matheus

Reputation: 147

Require class with pure Ruby

I'm with the following problem:

I'd like to require a 'config/application.rb' file to my index.rb.

In my task, I have to use pure Ruby.

config/application

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

But I got this error:

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

I tried to use require_relative too, but I got the following error:

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

Upvotes: 0

Views: 552

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

require 'config/application'

In Ruby, files included with Kernel#require must generally be in the $LOAD_PATH or given as relative paths, and don't include the filename extension. Some examples include:

  • Add the script's directory to your $LOAD_PATH.

    $:.unshift File.dirname(__FILE__)
    require 'config/application'
    
  • Require a file relative to the current working directory.

    require './config/application'
    

You might also use Kernel#load with an absolute path. For example:

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

Upvotes: 4

Related Questions