看了 rails 实现的 callback 代码,写个测试代码学习一下
module Callback
def initialize
around_method_name, around_method_block = *self.class.instance_variable_get(:@around_methods).first
self.instance_eval "alias :_temp :#{around_method_name}"
self.define_singleton_method around_method_name do |*args|
around_method_block.call lambda { self._temp(*args) }
end
end
def self.included base
base.extend CallbackMethods
end
module CallbackMethods
def around method, &block
@around_methods ||= []
@around_methods << [ method, block ]
end
end
end
class Test
include Callback
def initialize
super
end
around :hello do |x|
puts 'before hello'
x.call
puts 'after hello'
end
def hello world
puts "hello #{world}"
end
end
Test.new.hello 'world'
=>
before hello
hello world
after hello