From: kimura w. <ki...@us...> - 2005-04-26 15:09:28
|
Hi, I'm sorry my reply is too late. Tue, 12 Apr 2005 10:38:50 +0100, Jonathan Paisley wrote: >Hi, > >After following the instructions on the FAQ [1], with a few fiddles, I >have got Cocoa bindings on a Ruby object to work well. Please let me >know what you think of these modifications - if they seem ok I'll try >to update the Wiki FAQ page. > >The main thing I wanted to support was notification from Ruby to Cocoa >upon changing a value in Ruby. > >The kvc_accessor meta-method takes care of wrapping the setter (key=) >with the Cocoa bindings notifications. If the setter is already >defined, it will be wrapped by the kvc_accessor: > > class MyModel < OSX::NSObject > def foo=(value) > @foo = value > @foo_parsed = ... # do some parsing of foo > end > > kvc_accessor :foo # wraps foo= with notification, also defines foo >reader method > end > >Now, in other code, if you do 'model.foo = "Something"', any GUI >objects bound will automatically update. > It's cool! If you allow, I will add kvc_accessor to RubyCocoa. btw, Module#method_added enables to hook method definition. Following code reverts a wrapper of a setter when the setter is overrided. module NSBehaviorAttachment def kvc_accessor(*keys) # define setter if needed # alias setter to internal setter # define wrapper # alias wrapper to setter end def kvc_internal_setter(key) # returns wrapped setter name end def kvc_setter_wrapper(key) # returns wrapper name end def method_added(sym) return unless sym.to_s =~ /([^=]+)=\z/ key = $1 setter = kvc_internal_setter(key) wrapper = kvc_setter_wrapper(key) return unless method_defined?(setter) && method_defined?(wrapper) # do not re-alias wrapper return if self.instance_method(wrapper) == self.instance_method(sym) # re-alias wrapper to setter alias_method sym, wrapper end end -- kimura wataru |