从模块中定义的类方法注入回调

时间:2013-06-13 15:12:03

标签: ruby-on-rails ruby module callback

我想模仿AR对after_save ..., if: -> { bar? }的作用,但我不明白如何更改上下文以将self设置为该对象。

module MyModule
  extend ActiveSupport::Concern

  module ClassMethods
    def add_callback(options)
      foo = options.fetch(:foo)

      the_real_callback = -> do
        puts foo.call(self).inspect
      end

      before_save(the_real_callback)
    end
  end
end

class MyClass < ActiveRecord::Base
  include MyModule

  add_callback foo: ->(instance) { instance.bar }

  def bar
    "bar"
  end
end

o = MyClass.new
o.save
# displays "bar"

我想将add_callback foo: ->(instance) { instance.bar }替换为add_callback foo -> { bar }

1 个答案:

答案 0 :(得分:2)

谢谢@apneadiving,代码现在是:

module MyModule
  extend ActiveSupport::Concern

  module ClassMethods
    def add_callback(options)
      foo = options.fetch(:foo)

      the_real_callback = -> do
        puts instance_exec(&foo)
      end

      before_save(the_real_callback)
    end
  end
end

class MyClass < ActiveRecord::Base
  include MyModule

  add_callback foo: -> { bar }

  def bar
    "bar"
  end
end

o = MyClass.new
o.save
# displays "bar"