In Rails 3.0.5 & Ruby 1.9.3, is it possible to define the body of an around_save
callback inline with the around_save
declaration?
That is, I've noticed that this case works properly:
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
Whereas if I put the body inline, I get a 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>'
I tried changing yield
to yield activity
in the second example, but I got the same result. Is it possible to have my around_save
body be inline with the around_save
declaration?
In this case ActiveRecord
will pass a Proc
as a second argument, simply do this:
around_save do |activity, block|
puts 'before save'
block.call
puts 'after save'
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With