Forum: Ruby dynamically define attr_accessors on objects?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5e8fd591aeccbffd6fc93c171ac4fa43?d=identicon&s=25 Aaron Smith (warhero)
on 2007-06-25 18:23
How can I dynamically define attr_accessors on an object?

EX:;:
class Person
  attr_accessor :firstname
end
p = Person.new
p.firstname = 'aaron'
p.instance_variable_set(:@lastname, 'smith')
puts p.inspect
puts p.firstname
puts p.lastname

the last line generates an "undefined method lastname" error..

any ideas?
thanks
912c61d9da47754de7039f4271334a9f?d=identicon&s=25 MenTaLguY (Guest)
on 2007-06-25 18:31
(Received via mailing list)
On Tue, 26 Jun 2007 01:23:44 +0900, Aaron Smith
<beingthexemplary@gmail.com> wrote:
> How can I dynamically define attr_accessors on an object?
>
> EX:;:
> class Person
>   attr_accessor :firstname
> end
> p = Person.new
> p.firstname = 'aaron'

class << p
  attr_accessor :lastname
end
p.lastname = 'smith'

> puts p.inspect
> puts p.firstname
> puts p.lastname

You have to explicitly create the accessor methods; you don't get them
automatically when setting an instance variable.

-mental
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-06-25 19:31
(Received via mailing list)
On 25.06.2007 18:23, Aaron Smith wrote:
> puts p.firstname
> puts p.lastname
>
> the last line generates an "undefined method lastname" error..
>
> any ideas?

Use OpenStruct.

  robert
D3944ff4e8bc05067a615579b6ef599b?d=identicon&s=25 Phil Tomson (Guest)
on 2007-06-26 02:54
(Received via mailing list)
On 6/25/07, Aaron Smith <beingthexemplary@gmail.com> wrote:
> puts p.firstname
> puts p.lastname
>
> the last line generates an "undefined method lastname" error..
>
> any ideas?
> thanks
>
> --

I suppose you could do something like:

  class Person
   def def_accessor name, val=nil
     self.class.class_eval { attr_accessor name.intern }
     instance_variable_set ( "@#{name}".intern, val )
   end
 end

Then you could do something like:
h = { "fooname"=>"Foo", "age"=>28 }
h.each {|key,value|  p.def_accessor key, value }


...but the other suggestion to use OpenStruct is probably a better idea.

Phil
5e8fd591aeccbffd6fc93c171ac4fa43?d=identicon&s=25 Aaron Smith (warhero)
on 2007-06-26 05:32
thanks for the suggestions.. went with the openstruct.
This topic is locked and can not be replied to.