ruby: how to load .rb file in the local context

disfated picture disfated · Oct 29, 2010 · Viewed 10.6k times · Source

How this simple task can be done in Ruby?
I have some simple config file

=== config.rb
config = { 'var' => 'val' }

I want to load config file from some method, defined in main.rb file so that the local variables from config.rb became local vars of that method.
Something like this:

=== main.rb
Class App
    def loader
        load('config.rb') # or smth like that
        p config['var']   # => "val"
    end
end

I know that i can use global vars in config.rb and then undefine them when done, but i hope there's a ruby way )

Answer

Darwin picture Darwin · Oct 11, 2011

The config file.

{ 'var' => 'val' }

Loading the config file

class App
  def loader
    config = eval(File.open(File.expand_path('~/config.rb')).read)
    p config['var']
  end
end