2

Is there a way to know whether or not a method has been overridden by a subclass programmatically? Something that works like this:

class BaseModel
  def create
    puts "superclass"
  end
end

class SomeModel < BaseModel
  def create
    puts "subclass"
  end
end

puts SomeModel.overridden_instance_methods #=> [:create]

Any ideas?

Lance
  • 75,200
  • 93
  • 289
  • 503

1 Answers1

4
SomeModel.instance_methods(false) & BaseModel.instance_methods

The false makes instance_methods not include inherited methods. We then use set intersection to find all the methods that were defined on SomeModel which have previously been defined on BaseModel (or Object).

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 1
    BTW: if you don't know the direct superclass of `SomeModel` beforehand, you can use `SomeModel.superclass` instead of `BaseModel`. That way, you can package this functionality up in a reusable method. Something like `class Class; def overriden_methods; instance_methods(false) & superclass.instance_methods end end` And then: `SomeModel.overriden_methods` – Jörg W Mittag Aug 15 '10 at 16:38
  • Be aware, though, that this won't catch cases where SomeModel mixed-in a module that defined create(). This expression will only give you the methods that SomeModel has directly overridden. – jason.rickman Aug 15 '10 at 16:54
  • [Follow up question for modules](http://stackoverflow.com/questions/3488429/how-do-you-list-included-modules-in-a-ruby-class) – Lance Aug 15 '10 at 17:24