# Text file to code?

**URL:** <https://www.ruby-forum.com/t/text-file-to-code/123361>\
**Category:** Ruby\
**Created:** [December 17, 2007, 1:52am UTC](https://www.ruby-forum.com/t/text-file-to-code/123361 "2007-12-17T01:52:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pavel989](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/48db29/32.png) [@pavel989](https://www.ruby-forum.com/u/pavel989)\
**Post date:** [December 17, 2007, 1:52am UTC](https://www.ruby-forum.com/t/text-file-to-code/123361/1 "2007-12-17T01:52:36Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![pavel989](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/48db29/32.png) [@pavel989](https://www.ruby-forum.com/u/pavel989)\
**Post date:** [December 17, 2007, 3:06am UTC](https://www.ruby-forum.com/t/text-file-to-code/123361/2 "2007-12-17T03:06:49Z")

</div>

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/](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/](http://codeforpeople.com/lib/ruby/dynaload/)

---

<div class="post-metadata">

**Author:** ![pavel989](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/48db29/32.png) [@pavel989](https://www.ruby-forum.com/u/pavel989)\
**Post date:** [December 17, 2007, 5:29am UTC](https://www.ruby-forum.com/t/text-file-to-code/123361/3 "2007-12-17T05:29:27Z")

</div>

thank you so much
