Instantiating a class using Kernel.const_get

hello all,
i have a model which needs to instantiate a class depending on the
string name which is passed to initialize()

so, to get my Person class instance, i do:
person = Kernel.const_get(“Person”).send(“new”)
person.class => Person

#then i have a method which returns a hash of attributes
get_person_attributes.each do |att|
person.send("#{att}=", get_person_attributes[att])
end

person.inspect => #<Person …> #all the attributes look ok here

now come the problems. firstly, i tried just doing
person.update_attributes(get_person_attributes), which results in:

`new_record?’ for “Person”:String

and doing self.save gives the same error.

the models initialize method looks like:
def initialize(*args)
super(*args)
…other stuff
end

any ideas why i’m getting that error? I know update_attributes calls
save(), so they’re the same problem, but i can’t figure out what’s
causing save to be called on the string object.

thanks for reading.

On 18 May 2008, at 13:05, Paul F. wrote:

get_person_attributes.each do |att|
person.send("#{att}=", get_person_attributes[att])
end

person.inspect => #<Person …> #all the attributes look ok here

now come the problems. firstly, i tried just doing
person.update_attributes(get_person_attributes), which results in:

`new_record?’ for “Person”:String

What’s the backtrace like when this happens ?

Fred

May I ask why you’re using Kernel.const_get… what’s wrong with person

“Person”.constantize.new?

Then person.new_record? works for me.

On Mon, May 19, 2008 at 12:59 AM, Frederick C. <
[email protected]> wrote:

person = Kernel.const_get(“Person”).send(“new”)
person.update_attributes(get_person_attributes), which results in:

`new_record?’ for “Person”:String

What’s the backtrace like when this happens ?

Fred


Ryan B.
http://www.frozenplague.net
Feel free to add me to MSN and/or GTalk as this email.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs