Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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
You can’t perform that action at this time.