1

我想模仿 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 }

4

1 回答 1

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"
于 2013-06-13T16:00:04.583 回答