How to convert a string into class name?

I transfer a class name information (‘model’, a string) using a URL
params :id.
and I get the name using params[:id] in an controller action.
Now, how can I convert ‘model’ (string) into Model (class name) to
perform a Model.find(X)?

Nanyang Z. wrote:

I transfer a class name information (‘model’, a string) using a URL
params :id.
and I get the name using params[:id] in an controller action.
Now, how can I convert ‘model’ (string) into Model (class name) to
perform a Model.find(X)?

Try this:

params[:id].camelize.constantize

This will turn the string “my_super_cool_model” into the constant
(ie. the class) MySuperCoolModel.

Snowman wrote:

Try this:

params[:id].camelize.constantize

This will turn the string “my_super_cool_model” into the constant
(ie. the class) MySuperCoolModel.

it works! thanks.
btw, what’s the difference between .camelize and .classify?

btw, what’s the difference between .camelize and .classify?

You use classify when you’re starting with the plural version (eg. the
table name). So “my_super_cool_models”.classify => “MySuperCoolModel”

instance_variable_get("@#{object}").send(attribute)

I see. Thanks.

Now I know how to convert a string into a relative class name, like I
can make ‘user’ to User.

But what if I know ‘object’ (string) and ‘attribute’(string) when I want
to get a @object.attribute?
I’ll use this in helper method.

Sorry to revive such an old post, but I saw this and had to mention
something…

Snow Man wrote:

btw, what’s the difference between .camelize and .classify?

You use classify when you’re starting with the plural version (eg. the
table name). So “my_super_cool_models”.classify => “MySuperCoolModel”

While that’s true, classify is sometimes incorrect. Example:

‘email_address’.classify
=> “EmailAddres”

What I would suggest if you have the plural form, or if you’re not sure
what form you have, is to call singularize first, then camelize.
Example:

‘email_addresses’.singularize.camelize
=> “EmailAddress”

Snow Man wrote:

instance_variable_get("@#{object}").send(attribute)

Thanks!