From: Brian Candler on
Jesús Gabriel y Galán wrote:
> irb(main):051:0> C.add_method(:name) {@name}
> => #<Proc:0xb7cb9de8@(irb):51>
> irb(main):052:0> C.add_method(:name=) {|value| @name = value}
> => #<Proc:0xb7cb3bf0@(irb):52>
> irb(main):053:0> c = C.new
> => #<C:0xb7cb16d4>
> irb(main):054:0> c.name=3
> => 3
> irb(main):055:0> c.name
> => 3

Of course, since 'name' is static here, you could just include a module.

It gets more fun when the names of the accessors themselves are dynamic.
At this point it really does make more sense to use string eval, rather
than the alternative (instance_variable_get and instance_variable_set).

Have a look at define_method_attribute= in the following:
http://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_methods/write.rb

Also see define_read_method in attribute_methods/read.rb, and
method_missing in base.rb (this defines finder methods dynamically)
--
Posted via http://www.ruby-forum.com/.

From: Rajinder Yadav on
Brian Candler wrote:
> Jesús Gabriel y Galán wrote:
>> irb(main):051:0> C.add_method(:name) {@name}
>> => #<Proc:0xb7cb9de8@(irb):51>
>> irb(main):052:0> C.add_method(:name=) {|value| @name = value}
>> => #<Proc:0xb7cb3bf0@(irb):52>
>> irb(main):053:0> c = C.new
>> => #<C:0xb7cb16d4>
>> irb(main):054:0> c.name=3
>> => 3
>> irb(main):055:0> c.name
>> => 3
>
> Of course, since 'name' is static here, you could just include a module.
>
> It gets more fun when the names of the accessors themselves are dynamic.
> At this point it really does make more sense to use string eval, rather
> than the alternative (instance_variable_get and instance_variable_set).
>
> Have a look at define_method_attribute= in the following:
> http://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_methods/write.rb

Thanks for pointing out the path to ActiveRecord, I haven't gotten use
to browsing source code, this is really helpful!

>
> Also see define_read_method in attribute_methods/read.rb, and
> method_missing in base.rb (this defines finder methods dynamically)

cool I will do that =)


--
Kind Regards,
Rajinder Yadav

http://DevMentor.org

Do Good! - Share Freely