I am writing a module with method foo
, which calls a class method bar
on the receiver's class. My current approach is to use self.class.bar
, which works fine unless the class method is defined in an instance class instead of a "real" one:
module M
def foo
self.class.bar
end
end
obj = Object.new
class << obj
include M
def self.bar
42
end
end
obj.foo # => NoMethodError: undefined method `bar' for Object:Class
This makes sense because obj.class
does not return singleton classes. I could use obj.singleton_class
instead, and everything would run smoothly:
module M
def foo
self.singleton_class.bar
end
end
obj = Object.new
class << obj
include M
def self.bar
42
end
end
obj.foo # => 42
only if the method is defined on a singleton class for the same reason as above. Worse still, it creates a new singleton class for every receiver, something I want to avoid as these might be a fair amount of objects. So instead, I want some way to retrieve an object's singleton class if and only if it is already defined, i.e. something of the type obj.has_singleton_class ? obj.singleton_class : obj.class
. I couldn't find any way to perform this check though.