From: 7stud -- Date: 2011-04-15T09:01:01+09:00 Subject: Re: What do you do when you need to attach data to an object instance? Aaron D. Gifford wrote in post #992841: > What do you do when you see a need to be able to attach some data to > an object instance for later use somewhere else in a body of code? > Lately I've resorted to this: > > ## Generic utility to allow one to attach data with a getter/setter to > ## any instance of any object so long as there isn't a method name > ## collision: > def attach_data(obj, name, data) > getter = name.to_sym > setter = (name.to_s + '=').to_sym > raise "method name collision for #{obj.class} instance" if > obj.respond_to?(getter) || obj.respond_to?(setter) > ## The 'value' local variable will remain in existence in the lambda > closures below: > value = data > meta = class << obj ; self ; end > meta.send(:define_method, getter, lambda { value }) > meta.send(:define_method, setter, lambda {|val| value = val }) > 1) Note that you don't need to use send() there -- but maybe that's your preferred closure? Once you have the singleton class, you can define methods on it like this: def attach_data(obj, name, data) getter = name.to_sym setter = (name.to_s + '=').to_sym raise "method name collision for #{obj.class} instance" if obj.respond_to?(getter) || obj.respond_to?(setter) #value = data singleton = class <