Return to Snippet

Revision: 30501
at August 16, 2010 03:45 by viatropos


Initial Code
# 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)
    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.overrides?(method, parent_class = Object, within_tree = true)
    overridden_methods(parent_class, within_tree).include?(method.to_s)
  end
  
  def overrides?(method, parent_class = Object, within_tree = true)
    self.class.overrides?(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

Initial URL
return-array-of-overridden-methods-in-ruby-subclasses

Initial Description

                                

Initial Title
Return Array of Overridden Methods in Ruby Subclasses

Initial Tags
ruby

Initial Language
Ruby