Skip to content

Instantly share code, notes, and snippets.

@jeremyf
Forked from jnunemaker/gist:412580
Created May 25, 2010 02:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyf/412672 to your computer and use it in GitHub Desktop.
Save jeremyf/412672 to your computer and use it in GitHub Desktop.
# 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