From: ara.t.howard@... Date: 2006-05-12T00:04:51+09:00 Subject: Re: plz help with binding On Thu, 11 May 2006, Sergey Volkov wrote: > closure was created, but it was then shared between all class instances, so > Ara was absolutely right - we have to create new closure for each individual > instance, and this can not be implemented on class level (no instances > yet!); yes exactly - you must defer creation of the closure somehow. it must be an 'instance closure' instead of an 'instance variable' - we can get away from doing something at the instance level otherwise they all share the same 'thing' ;-) > I still do not want to modify class code to add instance_var-less storage, > so at this moment I have implemented external function to extend class with > new method (thanks, Ara!): > #!/bin/ruby > module M > def self.add_loc obj, name, ini=[] > skl = class << obj ; self ; end > skl.module_eval{ > v = ini > define_method name.to_sym, lambda{ v } > } > end > end yes, you are getting it - must be the lisp background, it took me a long time to get this stuff! > Any ideas about better API? use keywords - default paramerters are pure evil : some_method(42,true,true,true,false,2) #=> YUK vs some_method 42 :async => true, :block_size #=> 2 # AHHH ;-) so, for instance: harp:~ > cat a.rb class Object def singleton_class &b sc = class << self self end sc.module_eval &b if b sc end end class Module def vattr m, opts = {}, &b m = m.to_s reader = opts['reader'] || opts[:reader] writer = opts['writer'] || opts[:writer] query = opts['query'] || opts[:query] accessor = ![reader, writer].any? reader = "#{ m }" if reader or accessor writer = "#{ m }=" if writer or accessor query = "#{ m }?" if query or accessor define_method(reader) do singleton_class do val = b.call if b define_method reader, lambda{ val } end send reader end if reader define_method(writer) do |val| singleton_class do vattr(reader){ val } end send reader end if writer define_method(query) do not not send reader end if query [reader, writer, query] end def vattr_r m, opts = {}, &b opts.update 'reader' => true vattr m, opts, &b end def vattr_w m, opts = {}, &b opts.update 'writer' => true vattr m, opts, &b end end class C vattr('va'){ [] } end ca = C.new; ca.va << 10 cb = C.new; cb.va << 20 p ca.va #-> [10] p cb.va #-> [10] ca.va = {} cb.va = {} ca.va.update 'k' => 4 cb.va.update 'k' => 2 p ca.va? #-> true p ca.va #-> {"k"=>4} p cb.va? #-> true p cb.va #-> {"k"=>2} harp:~ > ruby a.rb [10] [20] true {"k"=>4} true {"k"=>2} regards. -a -- be kind whenever possible... it is always possible. - h.h. the 14th dali lama