views:

46

answers:

3

for example

str_modelname="User"

and i'd like to do

str_modelname.find(:first)

to find first User, but it doesn't work this way of course

+1  A: 

I'm having success with this snippet of code, but I won't claim that it's the best way:

str = "User"
p Kernel.const_get(str).find(:first)

I based this off of this technique.

Twisol
the question is, where the string comes from? if it's from the user, this can be unsafe...
giorgian
It seems like that's a problem inherent to the question rather than this particular solution.
Twisol
+6  A: 
str_modelname.classify.constantize.find(:first)
Damian
That's pretty awesome... +1
Twisol
While this solution is prettier than the one I provided, I still advocate mine, as it lets you limit the set of classes for which you can use it. Also, notice that you aren't checking for NameError and NoMethodError in case of wrong input.
giorgian
However this does answer the question. It is then up to the deeveloper to apply any guards required by the application.
Damian
+1  A: 

There are several ways, one of which may be using an hash, like:

models = {"User" => User, "AnotherModel" => AnotherModel}

And then:

models[name] ? models[name].find(:first) : nil

Why do you need this? There could be better solutions, depending on what you need to do.

giorgian