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