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