我正在尝试编写一个以编程方式将around_update
/around_destroy
回调添加到 ActiveRecord 模型的库。
因此,常规模型看起来像这样,并且可以按预期工作:
class User < ActiveRecord::Base
around_update :test_update
def test_update
Rails.logger.debug "test_update"
yield
Rails.logger.debug "Finished test_update"
end
end
u=User.last
u.name = 'something'
u.save
######### output (as expected):
# test_update
# Finished test_update
我的小图书馆(显然只是骨架)看起来像这样:
# A module for creating around callbacks in a model
module Piddle
module TimelineFor
def self.included(klass)
klass.send(:extend, ClassMethods)
end
module ClassMethods
def timeline_for(event, opts={})
method_name = :"timeline_for_#{event.to_s}"
define_method(method_name) do |&block|
Rails.logger.debug method_name.to_s
yield block
Rails.logger.debug "After yield in #{method_name.to_s}"
end
send(:around_update, method_name)
end
end
end
end
它定义了一个timeline_for 方法,该方法应该添加timeline_for_update 方法并将其作为around_update 事件的回调。我想使用的用户模型是这样的:
# second version of the User model using Piddle to create the callback
require 'piddle/piddle'
class User < ActiveRecord::Base
include Piddle::TimelineFor
timeline_for :update
end
u=User.last
u.name = 'gfgfhfhfgh'
u.save
在我看到的输出中
timeline_for_update
LocalJumpError: no block given (yield)
from /vagrant/lib/piddle/piddle.rb:13:in `block in timeline_for'
第一个输出行表示正在调用该方法,但没有传入该块。
有什么想法或替代实现吗?