From: Trans Date: 2006-11-15T20:50:05+09:00 Subject: Re: Proc as Observer Nobuyoshi Nakada wrote: > Hi, > > At Wed, 15 Nov 2006 12:15:05 +0900, > Trans wrote in [ruby-talk:225063]: > > But your's doesn't work for immutables like NilClass. It's a a > > bit more difficult in these cases. Have a clever solution? In any case > > I'll take this and what I have and add it to Facets. > > Sorry, I'm not sure what you expect for NilClass. Isn't this the > case? > > $ ./ruby -e 'nil.behaving(:foo){"Foo"}' -e 'p nil.foo' > "Foo" My mistake. It is for Symbols that it doesn't work. I was mistakingly thinking nil was the same, but that it not the case --which is great b/c it makes my code obsolete! :-) > > P.S. Would a cache on Behavior.new be a good optimization? > > It might be doubtful to be effective, since a Proc doesn't equal > another Proc created in the same place almost. Hmm... yes, I mean to go one step futher and catch the module and create methods within it: class Behavior < Module def define(behavior, &body) if body define_method(behavior, &body) else behavior.each do |behavior, body| if body define_method(behavior, &body) elsif body.nil? remove_method(behavior) else undef_method(behavior) end end end end end module Kernel def behaving(behavior, &body) unless @_behaviors extend(@_behaviors ||= Behavior.new) end @_behaviors.define(behavior, &body) end end T.