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

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


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']  endend


As others said, for configuration it's better to use YAML or JSON. To eval a file

binding.eval(File.open(File.expand_path('~/config.rb')).read, "config.rb")binding.eval(File.read(File.expand_path('~/config.rb')), "config.rb")

This syntax would allow you to see filename in backtraces which is important. See api docs [1].

Updated eval command to avoid FD (file descriptor) leaks. I must have been sleeping or maybe should have been sleeping at that time of the night instead of writing on stackoverflow..

[1] http://www.ruby-doc.org/core-1.9.3/Binding.html


You certainly could hack out a solution using eval and File.read, but the fact this is hard should give you a signal that this is not a ruby-like way to solve the problem you have. Two alternative designs would be using yaml for your config api, or defining a simple dsl.

The YAML case is the easiest, you'd simply have something like this in main.rb:

Class App  def loader      config = YAML.load('config.yml')      p config['var']   # => "val"  endend

and your config file would look like:

--- var: val