How to convert the string \"User\"
to User
?
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