Ruby on Rails内联around_save回调产生一个LocalJumpError

时间:2012-07-12 00:06:55

标签: ruby-on-rails ruby callback ruby-1.9

在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声明一致?

1 个答案:

答案 0 :(得分:10)

在这种情况下,ActiveRecord将传递Proc作为第二个参数,只需执行此操作:

around_save do |activity, block|
  puts 'before save'
  block.call
  puts 'after save'
end