Is there a way of checking whether an object has a singleton class without creating one?
Other than stated in Check if an object has a singleton class, it is not true that every object has a singleton class (see proof under https://repl.it/DuVJ/2).
The following approaches came into my mind, but don't work:
obj.singleton_class
This automatically creates a new singleton class if none exists (see https://ruby-doc.org/core-1.9.2/Object.html#method-i-singleton_class).
Using ObjectSpace
:
has_singleton_class = ObjectSpace.each_object(Class).any? do |klass|
klass < self.class && klass.singleton_class? && self.is_a?(klass)
end
This is very slow and might not work under jRuby as ObjectSpace
might not
be available.
obj.singleton_methods
only works if the singleton class has at least
one method.
You can use the ancestors
method. Because you want to check if a class (not an object) is a singleton, you can fetch all the modules mixed within the class and verify if any of those are a singleton class.
class Klass
include Singleton
end
Klass.ancestors.include? Singleton # true
In ruby, for creating a singleton you should include a Singleton
module. So if you check for that module it means that that class is a singleton. Ruby's base class inheritance of the module class meaning that you have access to use the ancestors
method.
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With