A .rb file without module, loading it inside a new module at runtime

Hi.

First my problem in general.

I have a ruby-gtk app. On startup, I load one .rb file.

Every method found in that file, will become a button.

When you click that button, that method is executed.

Right now, it does not work because I am not sure how to call a method
from one specific file ... when I only have the method name as a string.
(I am still stuck at this problem.)

I then wondered about something else though ...

Let's say I have a file with ruby code, without any modules inside.

Can I load the whole thing into a module at runtime?

Example in pseudocode:

  file = File.open('foobar.rb')
  Module.create(file)

The above would create a new module for the file 'foobar.rb' and the
name would be the filename without trailing .rb, the same as one would
do:

  module Foobar

At the beginning of that file.

Is that possible with ruby code at runtime?

···

--
Posted via http://www.ruby-forum.com/.

Well alright ...

I put the whole .rb file into a module now.

At least my problem was solved, even if it wasn't enough magic for me!

···

--
Posted via http://www.ruby-forum.com/.

Marc Heiler wrote in post #1026065:

Can I load the whole thing into a module at runtime?

Yes, but it's not especially pretty:

eval "module NewModule\n" + File.read("foobar.rb") + "\nend"

or:

module NewModule; end
NewModule.class_eval File.read("foobar.rb")

Note that modules don't actually have to have (constant) names:

mm = Module.new
mm.class_eval File.read("foobar.rb")

But if you do want to create a constant with a dynamic name, there's
const_set.

···

--
Posted via http://www.ruby-forum.com/\.