Topic: How to create instance of unknown class name?

Hi,

I'm trying to instantiate a class. But I don't know the name of the class. The class name is dynamic based on application input. For example, this doesn't work:

class_name = 'User'
user = class_name.new

What is the syntax for doing something like this?

Thank you.

Re: How to create instance of unknown class name?

Also, I'm trying to create a generic search method in my rails controllers. Something like:

@total = User.count(:conditions => conditions)

Where the class name (User) is unknown and the "conditions" is a real array that has already been populated. I've been messing around with eval but nothing works so far. Eval just throws an error and says that I can't add an array to a string. How do you use a real variable in eval? Any ideas?

Re: How to create instance of unknown class name?

goodieboy wrote:

Hi,

I'm trying to instantiate a class. But I don't know the name of the class. The class name is dynamic based on application input. For example, this doesn't work:

class_name = 'User'
user = class_name.new

What is the syntax for doing something like this?

Thank you.

This doesn't work?

class_name = 'user'
user = class_name.constantize.new

vinnie - rails forum admin

Re: How to create instance of unknown class name?

OK that worked. Thank you! I have So much to learn... smile