Ruby 一个实现 callback 的测试代码

zhb85 · 2022年05月04日 · 最后由 zzz6519003 回复于 2022年05月04日 · 326 次阅读

看了 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

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 没懂

需要 登录 后方可回复, 如果你还没有账号请 注册新账号