Skip to content

Instantly share code, notes, and snippets.

@chancancode
Forked from arthurnn/method_defined_within.rb
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chancancode/9485841 to your computer and use it in GitHub Desktop.
Save chancancode/9485841 to your computer and use it in GitHub Desktop.
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
if klass.method_defined?(name) || klass.private_method_defined?(name)
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
klass.instance_method(name).owner != superklass.instance_method(name).owner
else
true
end
else
false
end
end
class Foo
def hi; "hi"; end
end
class Bar < Foo
end
p method_defined_within?(:hi, Foo) # => true
p method_defined_within?(:hi, Bar) # => false
p method_defined_within?(:hi, Class.new(Bar)) # => false
module M
def say; "say what?"; end
end
class A
include M
end
module N
end
class Beta < A
include N
end
p method_defined_within?(:say, A) # => true
p method_defined_within?(:say, A, M) # => false
p method_defined_within?(:say, Beta) # => false
p method_defined_within?(:say, Beta, N) # => true (!!!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment