-
-
Save jeremyf/412672 to your computer and use it in GitHub Desktop.
This file contains 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
# I need class C to call the foo method for each module included | |
# that has the method foo. Order does not matter as much as each | |
# method getting called. alias method chain? | |
module ChainMethod | |
def chain_method(method_name) | |
base_method = instance_method(method_name.to_sym) | |
chained_method = included_modules.inject([base_method]) do |mem, mod| | |
if method = (mod.instance_methods.include?(method_name.to_s) ? mod.instance_method(method_name.to_sym) : nil) | |
mem << method | |
end | |
mem | |
end | |
define_method(method_name) { |*args| | |
chained_method.each {|method| | |
method.bind(self).call(*args) | |
} | |
} | |
end | |
end | |
module A | |
def foo | |
puts 'a' | |
end | |
end | |
module B | |
def foo | |
puts 'b' | |
end | |
end | |
class C | |
extend ChainMethod | |
include A | |
include B | |
def foo | |
puts 'c' | |
end | |
chain_method :foo | |
end | |
C.new.foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment