From: "Mauricio Fernández" Date: 2004-07-13T07:47:29+09:00 Subject: Re: Problems creating a method to define a class with its method On Tue, Jul 13, 2004 at 07:22:27AM +0900, Benny wrote: > def My_Module.subclass(name, &code) > eval <<-EOS > class #{name} < Bigclass > def #{name}.run(p) > super(p) > #{code.call} > end > end > EOS > end > end [...] > the problem is that the #{code.call} is executed before > the class is defined, so @test isn't filled yet (super(p) > isn't executed at this time. > > how can I change the code, so that �code� is part of the definition > of the class (i.e. part of its method �run�) batsman@tux-chan:/tmp$ cat ghfdgh54yiyh.rb module My_Module class Bigclass attr_accessor :test def Bigclass.run(para) @test = para puts "your parameter is " + @test end def Bigclass.check puts "I'm here" end end def My_Module.subclass(name, &code) k = Class.new(Bigclass) class << k; self end.send(:define_method, "run") do |p| super(p) instance_eval(&code) end My_Module.const_set(name, k) k end end My_Module.subclass("Newclass") do puts "does work work now: " + @test.to_s check end My_Module::Newclass.run "blah" batsman@tux-chan:/tmp$ ruby ghfdgh54yiyh.rb your parameter is blah does work work now: blah I'm here -- Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com "You, sir, are nothing but a pathetically lame salesdroid! I fart in your general direction!" -- Randseed on #Linux