From: Mark Hubbart Date: 2005-11-10T03:29:16+09:00 Subject: Re: Writing my own attr_* methods On 11/9/05, David Brady wrote: > Hi All, > > I frequently find myself creating member vars that contain a status flag > that want me to write a ? method. I know ruby can be tricked into > thinking it has an additional attr_ method, but off the top of my head I > can't think where I'd inject that method and how. > > I figure some guru will know what to do to Kernel, Class or Object to > make this work: > > ----------8<----------8<----------8<---------- > class Foo > attr_flag :bar, :baz > attr_flag_ro :qaz, :qux, :quux > > def initialize(qaz, qux, quux) > @qaz=qaz; @qux=qux; @quux=quux > @bar = @baz = false > end > end > > f = Foo.new(true, true, true) > > f.bar = true > f.baz = true > > puts "Yay!" if f.bar? > puts "Yay!" if f.baz? > puts "Yay!" if f.qaz? > puts "Yay!" if f.qux? > puts "Yay!" if f.quux? > ----------8<----------8<----------8<---------- > > I don't know if attr_flag, attr_flag_ro is the right pairing--perhaps > attr_flag would be read only and if you want it to be settable you want > to call attr_accessor, etc. > > Anyway, I'm not sure this is a perfect design, mostly I'm interested in > seeing *how* to write an attr_ method. > > Thoughts? attr_ methods are instance methods of Class. They define the desired accessor methods for that class when called: class Class def my_attr_reader(name) define_method(name){instance_variable_get "@#{name}" } end def my_attr_writer(name) define_method("#{name}="){|value| instance_variable_set "@#{name}", value} end end class Foo my_attr_reader :bar my_attr_writer :bar end f = Foo.new f.bar = 23 f.bar #==> 23 cheers, Mark > Thanks! > > -dB > > -- > David Brady > ruby_talk@shinybit.com > C++ Guru. Ruby nuby. Apply salt as needed. > > > >