None of the answers above worked for me, maybe because my code lives in the scope of a submodule.
I settled on creating a class_exists?
method in my module, using code found in Fred Wilmore's reply to "How do I check if a class is defined?" and finally stopped cursing.
def class_exists?(name)
name.constantize.is_a?(Class) rescue false # rubocop:disable Style/RescueModifier
end
Full code, for the curious:
module Some
module Thing
def self.build(object)
name = "Some::Thing::#{object.class.name}"
class_exists?(name) ? name.constantize.new(object) : Base.new(object)
end
def self.class_exists?(name)
name.constantize.is_a?(Class) rescue false # rubocop:disable Style/RescueModifier
end
private_class_method :class_exists?
end
end
I use it as a factory which builds objects depending on the class of the object passed as argument:
Some::Thing.build(something)
=> # A Some::Thing::Base object
Some::Thing.build(something_else)
=> # Another object, which inherits from Some::Thing::Base