Home > Software engineering >  ALternative to eval for string
ALternative to eval for string

Time:10-02

I have a string "Mymodel::FirstClass" stored in db and i need to call Mymodel::FirstClass (out from string). How to do this without using eval(string)?

CodePudding user response:

If you require Active Record, you can use constantize (see here)

So for example, something like this:

require "active_record"

"Mymodel::FirstClass".constantize
=> Mymodel::FirstClass

Or you can use const_get

Kernel.const_get("Mymodel::FirstClass")
=> MyModel::FirstClass

CodePudding user response:

You can use constantize as Stellenerger suggested. Or when the string might include a class names that might not exists then you might want to use safe_constantize which simply returns nil then the constant was not found instead of raising an exception:

"Mymodel::FirstClass".safe_constantize
#=> Mymodel::FirstClass

"NonExistingClass".safe_constantize
#=> nil
  • Related