Last active
January 5, 2016 08:17
-
-
Save deepak/eb8738218f422829496a to your computer and use it in GitHub Desktop.
how to find if a method is overridden
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://stackoverflow.com/questions/11462430/can-i-detect-that-a-method-has-been-overridden | |
module Ponger | |
def pong | |
"ping" | |
end | |
end | |
class HealthCheck | |
include Ponger | |
def ping | |
"pong" | |
end | |
end | |
class ImportantHealthCheck < HealthCheck | |
def ping | |
"the-pong" | |
end | |
def pong | |
"the-ping" | |
end | |
end | |
class AnotherHealthCheck < ImportantHealthCheck | |
end | |
x = HealthCheck.new | |
y = ImportantHealthCheck.new | |
z = AnotherHealthCheck.new | |
x.method(:ping).owner #=> HealthCheck | |
y.method(:ping).owner #=> ImportantHealthCheck | |
z.method(:ping).owner #=> ImportantHealthCheck | |
x.method(:pong).owner #=> Ponger | |
y.method(:pong).owner #=> ImportantHealthCheck | |
z.method(:pong).owner #=> ImportantHealthCheck | |
def overridden?(instance, method_name) | |
instance.method(method_name).owner == instance.class | |
end | |
overridden?(x, :ping) #=> true | |
overridden?(y, :ping) #=> true | |
overridden?(z, :ping) #=> false | |
module WTFPonger | |
def pong | |
"..." | |
end | |
end | |
class HealthCheck | |
include WTFPonger | |
end | |
health_check = HealthCheck.new | |
health_check.method(:pong).owner #=> WTFPonger | |
# how to do somthing similar in Java ? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment