Skip to content

Instantly share code, notes, and snippets.

@bitmage
Created December 2, 2011 20:27
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 bitmage/1424715 to your computer and use it in GitHub Desktop.
Save bitmage/1424715 to your computer and use it in GitHub Desktop.
Attach Callbacks to Methods In a Module
#http://stackoverflow.com/questions/5513558/executing-code-for-every-method-call-in-a-ruby-module
module M
def self.before(*names)
names.each do |name|
m = instance_method(name)
define_method(name) do |*args, &block|
yield
m.bind(self).(*args, &block)
end
end
end
end
module M
def hello
puts "yo"
end
def bye
puts "bum"
end
before(*instance_methods) { puts "start" }
end
class C
include M
end
C.new.bye #=> "start" "bum"
C.new.hello #=> "start" "yo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment