How to convert the string "User" to User?
- Are you trying to call a variable function?wersimmon– wersimmon2010-03-02 06:55:09 +00:00Commented Mar 2, 2010 at 6:55
- 1I would also like an answer to this question; however, are you trying to create a new constant based on a string, OR find an already initialized constant? Also are you looking for vanilla ruby or also Rails?user3373470– user33734702015-08-26 20:37:20 +00:00Commented Aug 26, 2015 at 20:37
Add a comment |
4 Answers
Object.const_get("User") No need to require ActiveSupport.
1 Comment
Artur INTECH
Usage example:
class User; def self.lookup; const_get('SomeClassName);end; end User.lookup will return class itself.The recommended way is to use ActiveSupport's constantize:
'User'.constantize You can also use Kernel's const_get, but in Ruby < 2.0, it does not support namespaced constants, so something like this:
Kernel.const_get('Foobar::User') will fail in Ruby < 2.0. So if you want a generic solution, you'd be wise to use the ActiveSupport approach:
def my_constantize(class_name) unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ class_name raise NameError, "#{class_name.inspect} is not a valid constant name!" end Object.module_eval("::#{$1}", __FILE__, __LINE__) end 3 Comments
Drenmi
Since Ruby 2.0 has reached EOL, there is no longer any need to pull in ActiveSupport as a dependency to reference a constant with a string. :-)
Eric Walker
See also
'User'.safe_constantizeAdam Grant
Recommended by whom?