Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Inline around_save Callback Yields a LocalJumpError

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?

like image 907
maksim Avatar asked Dec 20 '22 19:12

maksim


1 Answers

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
like image 196
sikachu Avatar answered Dec 27 '22 19:12

sikachu