From: "David A. Black" Date: 2008-10-20T20:19:10+09:00 Subject: Re: define_method inside a module Hi -- On Mon, 20 Oct 2008, MR Damien wrote: > Joel VanderWerf wrote: >> MR Damien wrote: >>> def add(object) >>> end >>> end >>> end >>> end >>> undefined method `define_method' for # (NoMethodError) >> >> Try working in the singleton class: >> >> class C >> def foo >> class << self >> define_method :bar do puts "BAR"; end >> end >> end >> end >> >> c = C.new >> c.foo >> c.bar > > Hi, > > seems not to work neither > > > ------------------ > def add(object) > name = "@" + self.collection_name_for(object) > > if self.instance_variable_get(name) > self.instance_variable_get(name) << object > else > self.instance_variable_set(name, Array.new) > self.instance_variable_get(name) << object > > class << self > define_method(name) do > instance_variable_get("@#{name}") > end > end > > end > end > ------------------ > in `define_method': interning empty string (ArgumentError) That's because name is not in scope inside the class definition body (class << self). In order to keep name in scope, you need to use class_eval on the singleton class. That way, you're operating inside a code block, which does share the local variables. (class << self; self; end).class_eval do define_method(name) do etc. David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!