How to turn a string into a class name, but only if this class already exists?
If Amber is already a class, I can get from string to class via:
Object.const_get("Amber")
or (in Rails)
"Amber".constantize
But any of them will not work with NameError: uninitialized constant Amber if Amber is not a class yet.
My first thought is to use the defined? method defined? , but it does not distinguish between existing classes and those that do not:
>> defined?("Object".constantize) => "method" >> defined?("AClassNameThatCouldNotPossiblyExist".constantize) => "method"
So, how do I check if a string names a class before I try to convert it? (Okay, what about the begin / rescue block to catch NameError errors? Too ugly? I agree ...)
ruby class ruby-on-rails-3 defined
fearless_fool Apr 22 2018-11-18T00: 00Z
source share