Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access class if class method is overwritten

Tags:

ruby

Here is an external class which has its class method overwritten.

class Foo
  def class
    "fooo"
  end
end

class Boo < Foo
end

class Moo < Foo
end

Now I have an instance of the subclass. Is it possible to find out which class it belongs to?

foo.class # currently returns 'fooo', I want get Boo or Moo.
like image 823
lulalala Avatar asked Nov 28 '22 21:11

lulalala


1 Answers

You could use instance_method to grab the class method from somewhere safe (such as Object) as an UnboundMethod, bind that unbound method to your instance, and then call it. For example:

class_method = Object.instance_method(:class)
# #<UnboundMethod: Object(Kernel)#class> 

class_method.bind(Boo.new).call
# Boo 

class_method.bind(Moo.new).call
# Moo 

class_method.bind(Foo.new).call
# Foo 

Of course, if you've also replaced Object#class (or Kernel#class) then all bets are off and you're in a whole new world of pain and confusion.

like image 95
mu is too short Avatar answered Dec 07 '22 23:12

mu is too short