Module: Nuggets::Object::SingletonClassMixin

Included in:
Object
Defined in:
lib/nuggets/object/singleton_class_mixin.rb

Instance Method Summary (collapse)

Instance Method Details

- (Object) singleton_class Also known as: virtual_class, ghost_class, eigenclass, metaclass, uniclass

call-seq:

object.singleton_class => aClass

Returns the singleton (or virtual/eigen/meta) class associated with object.



36
37
38
# File 'lib/nuggets/object/singleton_class_mixin.rb', line 36

def singleton_class
  class << self; self; end
end

- (Boolean) singleton_class? Also known as: virtual_class?, ghost_class?, eigenclass?, metaclass?, uniclass?

call-seq:

object.singleton_class? => +true+ or +false+

Returns true if object is a singleton_class (i.e., has a singleton_object), false otherwise.

Returns:

  • (Boolean)


81
82
83
84
85
86
# File 'lib/nuggets/object/singleton_class_mixin.rb', line 81

def singleton_class?
  singleton_object
  true
rescue ::TypeError
  false
end

- (Object) singleton_object Also known as: virtual_object, ghost_object, eigenobject, metaobject, uniobject, singleton_instance

call-seq:

object.singleton_object => anObject

Returns the object of which object is the singleton_class. Raises a TypeError if object is not a singleton class.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/nuggets/object/singleton_class_mixin.rb', line 51

def singleton_object
  [true, false, nil].each { |obj|
    return obj if self.equal?(obj.singleton_class)
  }

  # raises TypeError if neither class nor module
  ::ObjectSpace.each_object(self) { |obj|
    return obj if self.equal?(obj.singleton_class)
  }

  # if we got here, it can't be a singleton class
  # or its singleton object doesn't exist anymore
  raise ::TypeError
rescue ::TypeError
  raise ::TypeError, 'not a singleton class'
end