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
11155
(-- --)
February 5, 2010, 4:16pm
2
Try the eval method.
For instance:
classname = "Date"
=> "Date"
eval(classname).today
=> Fri, 05 Feb 2010
11155
(-- --)
February 5, 2010, 4:32pm
3
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,
rab
(Rob Biedenharn)
February 5, 2010, 4:40pm
4
Try the eval method.
For instance:
classname = "Date"
=> "Date"
eval(classname).today
=> Fri, 05 Feb 2010
With ActiveSupport you get constantize.
constantize("Date")
=> Date
You can either look at the ActiveSupport implementation or this one:
# from Jim Weirich (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 Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
Works great now. Thank you.
Modified Code:
model_name = "User"
@Model = model_name.constantize
@Model.find (params[:id]).name
11155
(-- --)
February 5, 2010, 10:22pm
6
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,