From: Robert Dober Date: 2007-08-24T20:23:05+09:00 Subject: Re: Dynamic methods On 8/24/07, Marcin Miel�y�ski wrote:> Trans wrote:>> > Also, keep in mind Ruby classes are open. You can add real methods to> > them on the fly.> >> > class Example> > end> >> > foo = "bar"> >> > Example.class_eval %{> > def #{foo}> > "#{foo}"> > end> > }> >>> It's better not to use string evals:>> Example.class_eval do> define_method foo do> "#{foo}"> end> end>> lopex You are right for sure here Marcin, however are you aware that the twoare not exactly the same? In case you get bitten by define_methodmaybe Ara's recent post about instance_eval{ def ... } might behelpful,the following is a "String-eval-free" way to define a method on aclass *without* being exposed to the closure of the currentenvironment.----------------------- 8< ---------------------- value = 222 ## evil closure variable shadowing A#value class A class << self def value; 1120 end # just to show that Ara's method works end def value; 101010 end # the value we really wantend A.class_eval %{ def tom; value end} ## works but we use the threaded String eval :( A.class_eval do define_method :marcin do value end # value is the closure of course :(end ## nice, but does not work :( class A class << self alias_method :old_new, :new def new *args, &block o = old_new( *args, &block ) o.instance_eval do def ara; value end end o end endend ## this does the trick, simple concise, trivial :( well we wish it were.## and there are issues with the alias it is a potential redefeinition disaster a = A.newp [:tom, a.tom]p [:marcin, a.marcin]p [:ara, a.ara] CheersRobert -- I'm an atheist and that's it. I believe there's nothing we can knowexcept that we should be kind to each other and do what we can forother people.-- Katharine Hepburn