On Sun, Aug 15, 2004 at 04:31:11AM +0900, Claus Spitzer wrote:
> Greetings again! I'm trying to create a user-defined class on the fly.
> The idea would be for the user to provide a class name, maybe a
> superclass name, and some method definition as a string, e.g.
[...]
> So far so good. Security is not a concern, this is just for a proof of
> concept. But I would like to be able to then extend MyClass
> separately, e.g.
> 
>   module Mod
>     def bar
>        p "foo!"
>     end
>   end
> 
>   class ???
>      include Mod
>   end
> 
> I'm stuck on the ??? part. I tried 

>> def make_class(name, p, code); r = Class.new(p.split(/::/).inject(Object){|s,x|s.const_get(x)}); Object.const_set(name, r); r.module_eval code; r end
=> nil
>> class A; class B; end end
=> nil
>> klass = make_class "Foo", "A::B", "def bar; 'bar' end"
=> Foo
>> klass.ancestors
=> [Foo, A::B, Object, Kernel]
>> klass.new.bar
=> "bar"

You can later modify klass dynamically with module_eval, define_method,
etc.

-- 
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com