在Rails 3.0.5& Ruby 1.9.3,是否可以使用around_save
声明内联定义around_save
回调的主体?
也就是说,我注意到这种情况正常:
around_save :around_save_body
def around_save_body
puts 'before save'
yield
puts 'after save'
end
[114] pry(main)> a = Activity.find(57)
=> #<Activity id: 57, ... >
[115] pry(main)> a.save
before save
after save
=> true
然而,如果我将主体内联,我得到一个LocalJumpError:
around_save do |activity|
puts 'before save'
yield
puts 'after save'
end
[117] pry(main)> a = Activity.find(57)
=> #<Activity id: 57, ... >
[118] pry(main)> a.save
before save
LocalJumpError: no block given (yield)
from /home/maksim/hkn/website/app/models/activity.rb:47:in `block in <class:Activity>'
我尝试在第二个示例中将yield
更改为yield activity
,但我得到了相同的结果。是否可以让我的around_save
正文与around_save
声明一致?
答案 0 :(得分:10)
在这种情况下,ActiveRecord
将传递Proc
作为第二个参数,只需执行此操作:
around_save do |activity, block|
puts 'before save'
block.call
puts 'after save'
end