views:

140

answers:

3

Hey guys, I'm playing around with the new Rails 3 API and I have a question regarding the new method run_callbacks(kind, *args, &block)

In the following code:

class User < ActiveRecord::Base
  before_save :say_hi
  after_save :say_bye

  private

    def say_hi; puts "hi"; end

    def say_bye; puts "bye"; end

end

I can explicit call the callbacks on save by running:

> u.run_callbacks(:save)
hi
bye
=> true

But my question is, how I can only run the *before_save* or *after_save* callback?

Reviewing the run_callbacks(kind, *args, &block) code:

# File activesupport/lib/active_support/callbacks.rb, line 92
def run_callbacks(kind, *args, &block)
  send("_run_#{kind}_callbacks", *args, &block)
end

I don't know how to build *args to only call before or after callbacks, I tried something like u.run_callbacks(:before_save) (gives me undefined method error) and u.run_callbacks(:save, :before) runs all the save callbacks (before and after).

Any help would be appreciated, thanks!

A: 

This is untested but after reading the documentation I think it might work

something.run_callbacks :save do
  before_save
end

I'll go test it out actually I think.

Ok so it's not working. From the source I read, I don't think you can run callbacks of the same kind separately.

Hugo
What does that exactly return? I can't test it right now.
jpemberthy
undefined method error
Hugo
+1  A: 

I'm still looking into how to do the after_save only, but to run JUST the before_save callback, you can do something like:

u.run_callbacks(:save) { false }

This should cancel the callbacks after the before_save ones are run.

vegetables
+2  A: 

Looks like you are running into a bug in Rails 3.0. It appears to be in the queue for 3.0.1 as mentioned in this lighthouse ticket.

As @vegetables says, you can at least get the before_save callbacks to fire by sending false to run_callbacks(:save).

Brian
Yep, It seems like we'r not able to run `before` or `after` save callbacks individually :(, at least in a cleaner way :P.
jpemberthy
@jpemberthy - if you update your question with a specific use case, perhaps we can figure out a workaround that will suffice until the bug is addressed?
Brian
@brian, thanks, but that's not necessary, I was just playing with the new API (thanks god) It's not a thing to migrate from 2.3.x or something I'm working on :P
jpemberthy