Define a string as a Model object

Good morning,

I’m trying to dynamically define models.

This method #1 works:
model_name = User
@Model = model_name
@Model.find(params[:id]).name

This method #2 doesn’t:
model_name = “User”
@Model = model_name
@Model.find(params[:id]).name

Anyone know how I can get method #2 to work? Is there something I can
tack onto the end of ‘model_name’ to get it to know that it’s a model?

Thanks,

Frank

Try the eval method.

For instance:

classname = “Date”
=> “Date”
eval(classname).today
=> Fri, 05 Feb 2010

Frank_in_Tennessee wrote:

Good morning,

I’m trying to dynamically define models.

This method #1 works:
model_name = User
@Model = model_name
@Model.find(params[:id]).name

This method #2 doesn’t:
model_name = “User”
@Model = model_name
@Model.find(params[:id]).name

Of course not. In method 2, @Model is a String, not a Class.

Anyone know how I can get method #2 to work? Is there something I can
tack onto the end of ‘model_name’ to get it to know that it’s a model?

Look up the constantize method.

Thanks,

Frank

Best,
–Â
Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Works great now. Thank you.

Modified Code:

model_name = “User”
@Model = model_name.constantize
@Model.find(params[:id]).name

On Feb 5, 2010, at 11:16 AM, Sharagoz – wrote:

Try the eval method.

For instance:

classname = “Date”
=> “Date”
eval(classname).today
=> Fri, 05 Feb 2010

With ActiveSupport you get constantize.

irb> constantize(“Date”)
=> Date

You can either look at the ActiveSupport implementation or this one:

from Jim W. (based on email correspondence), improved by

Rick Denatale (in ruby-talk:332670)
def constantize(camel_cased_word)
camel_cased_word.
sub(/^::/,‘’).
split(“::”).
inject(Object) { |scope, name| scope.const_defined?(name) ?
scope.const_get(name) : scope.const_missing(name) }
end

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

Frank_in_Tennessee wrote:

Works great now. Thank you.

Modified Code:

model_name = “User”
@Model = model_name.constantize
@Model.find(params[:id]).name

Great. One other thing: @Model is unusual. You might consider @model
instead as being more idiomatic Ruby.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]