Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 )

like image 819
disfated Avatar asked Oct 29 '10 00:10

disfated


People also ask

How do I load files into IRB?

If you only need to load one file into IRB you can invoke it with irb -r ./your_file. rb if it is in the same directory. This automatically requires the file and allows you to work with it immediately. If you want to add more than just -r between each file, well that's what I do and it works.

How do I read a file in Ruby?

Opening a File in Ruby There are two methods which are widely used − the sysread(n) and the read() method. The open method is used to open the file, while the sysread(n) is used to read the first "n" characters from a file, and the read() method is used to read the entire file content.

What happens when you require a file in Ruby?

In Ruby, the require method is used to load another file and execute all its statements. This serves to import all class and method definitions in the file.


2 Answers

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
like image 113
Darwin Avatar answered Sep 28 '22 21:09

Darwin


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

like image 30
akostadinov Avatar answered Sep 28 '22 20:09

akostadinov