Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails pass params/arguments to ActiveRecord callback function

Tags:

I have the snippet below in one of my AR models:

after_update :cache_bust 

The cache_bust method in the model accepts a parameter (boolean) that sets the value of itself to false by default.

How can I pass true to this method in the model from my ActiveRecord callback defined above it?

Ex: after_update :cache_bust(true) does not work because it's a symbol, how can I pass true to the method's param?

like image 489
Noah Avatar asked May 13 '15 17:05

Noah


2 Answers

There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects, inline methods (using a proc), and inline eval methods (using a string).

Try this?

after_update -> { cache_bust(true) } 
like image 172
Nick Veys Avatar answered Jan 03 '23 10:01

Nick Veys


Based on your clarification, you can achieve what you're looking for by using optional method parameters, like so:

def cache_bust(callback = true)     ... method body end 

In the scenario where the method is called from the after_update callback, the parameter is not passed, but defaults to true. Otherwise, if the method is called from anywhere else "manually", you have the option of passing whatever value you wish to that method.

like image 25
Paul Richter Avatar answered Jan 03 '23 12:01

Paul Richter