Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you manually "trigger" a callback in Ruby on Rails?

I'm trying to run all callback methods manually inside a method. For example, I want to run all "before_destroy" methods inside my model.

Is there a way to manually trigger this? For example, something like:

def some_method
  # ...
  trigger(:before_destroy)
end

which will then run all methods that I have declared with "before_destroy :...."

Any ideas?

like image 419
sjsc Avatar asked Sep 29 '14 22:09

sjsc


1 Answers

If you're happy to run both :before and :after hooks, you can try run_callbacks. From the docs:

run_callbacks(kind, &block)

Runs the callbacks for the given event.

Calls the before and around callbacks in the order they were set, yields the block (if given one), and then runs the after callbacks in reverse order.

If the callback chain was halted, returns false. Otherwise returns the result of the block, or true if no block is given.

run_callbacks :save do
  save
end
like image 55
Abraham Chan Avatar answered Nov 11 '22 17:11

Abraham Chan