[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

dynamically define attr_accessors on objects?

warhero

6/25/2007 4:24:00 PM

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

--
Posted via http://www.ruby-....

4 Answers

MenTaLguY

6/25/2007 4:29:00 PM

0

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


Robert Klemme

6/25/2007 5:26:00 PM

0

On 25.06.2007 18:23, Aaron Smith wrote:
> 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?

Use OpenStruct.

robert

rubyfan

6/26/2007 12:53:00 AM

0

On 6/25/07, 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'
> 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
>
> --

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

warhero

6/26/2007 3:32:00 AM

0

thanks for the suggestions.. went with the openstruct.

--
Posted via http://www.ruby-....