dynamically define attr_accessors on objects?

A

Aaron Smith

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
 
M

MenTaLguY

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
 
R

Robert Klemme

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
 
P

Phil Tomson

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,282
Latest member
RoseannaBa

Latest Threads

Top