Text file to code?

earlier i asked if its possible to load a string as code. but now, lets
say i have a config file. a text file with ruby code in it. how can i
load that into my ruby code? but for that matter, everytime it does load
it, can it read as a new object? like lets say the config file consists
of “plugins” and i add one, can ruby pick it up while the app is
running?

Pavel P. wrote:

earlier i asked if its possible to load a string as code. but now, lets
say i have a config file. a text file with ruby code in it. how can i
load that into my ruby code? but for that matter, everytime it does load
it, can it read as a new object? like lets say the config file consists
of “plugins” and i add one, can ruby pick it up while the app is
running?

You can do that by wrapping the loaded code in a module, and then using
that module to access any constants or functions defined in the code.
Here’s how I do that:

http://redshift.sourceforge.net/script/

An adaptation of this is in the facets gem, IIRC. The basic idea is
simple (suggested by Nobu Nokada):

def load_in_module(file)
module_eval(IO.read(file), File.expand_path(file))
end

This returns a module that you can use to get at stuff in the file:

m = load_in_module(file)
m::SomeClass
m.some_method

The code above assumes that the file has these definitions:

class SomeClass;…end
def self.some_method;…end

An alternative:

http://codeforpeople.com/lib/ruby/dynaload/

thank you so much

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs