在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 yield,但我得到了相同的结果.是否可以让我的around_save主体与around_save声明内联?
解决方法
在这种情况下,ActiveRecord将传递Proc作为第二个参数,只需执行以下操作:
around_save do |activity,block| puts 'before save' block.call puts 'after save' end