Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object has a singleton class (eigenclass) without creating one

Tags:

ruby

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:

  1. 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).

  2. 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.

  3. obj.singleton_methods only works if the singleton class has at least one method.

like image 702
Remo Avatar asked Oct 12 '16 15:10

Remo


1 Answers

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:

  1. https://ruby-doc.org/core-2.1.0/Module.html#method-i-ancestors
  2. https://ruby-doc.org/core-2.2.0/Class.html
  3. https://ruby-doc.org/stdlib-2.1.0/libdoc/singleton/rdoc/Singleton.html#module-Singleton-label-Usage
like image 107
Roy Cruz Avatar answered Sep 28 '22 16:09

Roy Cruz