Convert string into class name without throwing error
I am trying to convert the string into classname using constantize. But it throws error if the classname is not present or the string is empty or nil
.
Is there any way to convert the string into classname without throwing error. Or returning false only if not able to convert.
I hate Rails, it brings a ton of redundant so-called helpers, having zero value in general. This might be easily done with pure Ruby:
Kernel.const_get(string) if Kernel.const_defined?(string)
The above effectively returns the class or nil
(which is falsey in Ruby) if the class is not defined.
Firstly, I want to point out something from the answers above. rescue false
means that all kinds of exceptions thrown from that expression are rescued as false. This means that even if you have an exception object of class NoMethodError
or RuntimeError
you will return false
and your expectation would be that the constantized string does not match a constant in your app. This can cause you hours of debugging if you don't know how the error handling system in ruby is working. It is also a place to introduce a lot of bugs in your code in the future.
I see the ruby-on-rails tag so I assume you are running a problem in a rails app. You can use a helper method coming from the ActiveSupport::Inflector
module. Instead of rescuing the constantize
method you would probably want to use the safe_constantize
. It will return nil
in case the constant is not present in your project.
Example usage (note I haven't defined a Foo
constant in my project):
# with constantize
irb(main) > 'foo'.constantize
=> NameError (wrong constant name foo)
# with safe_contantize
irb(main) > 'foo'.safe_constantize
=> nil