From: Mark Hubbart Date: 2005-01-01T06:43:12+09:00 Subject: Re: attr / attr_accessor On Thu, 30 Dec 2004 22:34:40 +0900, Markus Werner wrote: > Hi Ruby Folk, > > I'm quite a newbie in programming. Last year I came to perl and now I'm > testing ruby. > > I like the methods attr, attr_*. But there is one drawback. You can't tell the > methode that there should be a standard code that will be executed on every > access. IMHO The best would be a pre and a posthook. Perhaps: class Module def attr_writer_proc(*args, &block) names = args.map{|s| s.to_sym} names.each do |name| define_method "#{name}=" do |val| instance_variable_set "@#{name}", block.call(val) end end end def attr_reader_proc(*args, &block) names = args.map{|s| s.to_sym} names.each do |name| define_method name do block.call instance_variable_get("@#{name}") end end end end This would act as a combo pre-hook and data filter: class Foo # make sure the values are strings attr_writer_proc :foo, :bar do |val| val.to_str end # we only want to store copies the objects passed attr_writer_proc(:baz){|val| val.dup } # log changes to quux attr_writer_proc(:quux){|val| log("setting quux to %p"%[val]); val } end this could conceivably be wrapped up into the attr_writer/attr_reader methods, since they currently don't take blocks... Also, it might be handy to check the arity of the block and pass the variable name as an optional second argument. hth, Mark