From: Gavin Kistner Date: 2005-09-19T21:37:29+09:00 Subject: Re: Metaprogramming problem --Apple-Mail-2-649870537 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed On Sep 19, 2005, at 6:16 AM, Clifford Heath wrote: > Ok, I can see why "block" isn't defined. How can I pass add_property's > block in as a block to be used *inside* the evaluated code? Here's *a* working solution. The big string + eval feels like a serious hack, but I'm not cool enough to know how to deal with it properly. class Object def add_property(sym, &block) n = sym.id2name (@_property_callbacks||={})[ n ] = block code = %Q{ def #{n}() @#{n} ||= nil end def #{n}=(value) if block = @_property_callbacks[ '#{n}' ] @#{n} = block.call(value) else @#{n} = value end end } eval(code) end end # A test object: d = 3 # Add a getter and custom setter to 3: d.add_property(:do_it) {|v| # Custom setter method puts "d.do_it here, v = #{v.inspect}" v # No filtering this time, just return the value. } # Assign the property: d.do_it = "a value" --Apple-Mail-2-649870537--