DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Lance has posted 24 posts at DZone. View Full User Profile

Return Array Of Overridden Methods In Ruby Subclasses

08.15.2010
| 3133 views |
  • submit to reddit
        
# thanks to the answer here:
# http://stackoverflow.com/questions/3488203/how-do-i-see-where-in-the-class-hierarchy-a-method-was-defined-and-overridden-in
class Object
  def self.overridden_methods(parent_class = Object, within_tree = true)
    puts ancestors.inspect
    if within_tree
      defined_methods = ancestors[0..ancestors.index(parent_class) - 1].map { |object| object.instance_methods(false) }.flatten.uniq
      parent_methods = superclass.instance_methods
    else
      defined_methods = instance_methods(false)
      parent_methods = parent_class.instance_methods
    end
    defined_methods & parent_methods
  end
  
  def overridden_methods(parent_class = Object, within_tree = true)
    self.class.overridden_methods(parent_class, within_tree)
  end
  
  def self.overridden?(method, parent_class = Object, within_tree = true)
    overridden_methods(parent_class, within_tree).include?(method.to_s)
  end
  
  def overridden?(method, parent_class = Object, within_tree = true)
    self.class.overridden?(method, parent_class, within_tree)
  end
end

class ParentModel < Object
  def save; end
end

class ChildModel < ParentModel
  def save; end
  def create; end
  def to_s; end
end

class AnotherChildModel < ParentModel
  def save; end
end

class GrandChildModel < ChildModel
  def create; end
end

# what have you overridden from the base `Object` class
p ParentModel.overridden_methods(Object)
#=> []
p ParentModel.overridden_methods(Object, false)
#=> []
p ChildModel.overridden_methods(Object)
#=> ["to_s", "save"]
p ChildModel.overridden_methods(Object, false)
#=> ["to_s"]
p ChildModel.overridden_methods(ParentModel)
#=> ["to_s", "save"]
p ChildModel.overridden_methods(ParentModel, false)
#=> ["to_s", "save"]
p AnotherChildModel.overridden_methods(Object)
#=> ["save"]
p AnotherChildModel.overridden_methods(Object, false)
#=> []
p AnotherChildModel.overridden_methods(ParentModel)
#=> ["save"]
p AnotherChildModel.overridden_methods(ParentModel, false)
#=> ["save"]
p GrandChildModel.overridden_methods(Object)
#=> ["create", "to_s", "save"]
p GrandChildModel.overridden_methods(Object, false)
#=> []
p GrandChildModel.overridden_methods(ParentModel)
#=> ["create", "to_s", "save"]
p GrandChildModel.overridden_methods(ParentModel, false)
#=> []
p GrandChildModel.overridden_methods(ChildModel)
#=> ["create"]
p GrandChildModel.overridden_methods(ChildModel, false)
#=> ["create"]

# note, this probably won't work with modules overriding methods, it just needs to be tweaked a little more