alopez02
alopez02

Reputation: 1524

Executing a conditional method only one time for a callback with multiple methods. Rails

In a Rails app, I'm using an after_update call back that runs multiple methods upon passing a conditional method such as below:

app/models/my_model.rb

class MyModel < ApplicationRecord
  after_update :method_1, :method_2, :method_3, if: :this_happens?
  #some custom methods
private
  def this_happens?
    # a condition that returns true or false here
  end
end

I've noticed that the method this_happens? is executed three times, just before :method_1, :method_2, :method_3.

This make sense as any of those three call back methods could change the data in such a way that the condition has to be evaluated again to make sure it's met in every case. However, when you know those 3 methods are not changing the data in any way that could alter the condition evaluation, is it possible to run this_happens? only once and gain some efficiency?

I don't seem to find anything online and wonder if anyone could advise.

PS. using Rails 5.1

Upvotes: 1

Views: 468

Answers (1)

mdegis
mdegis

Reputation: 2528

Encapsulation is the one of the easiest way that you can choose to overcome this situation.

Just wrap your methods in another one, then it will only check this_happens? one time.

class MyModel < ApplicationRecord
  after_update :combine_methods, if: :this_happens?
  #some custom methods
private
  def combine_methods
    method_1
    method_2
    method_3
  end

  def this_happens?
    # a condition that returns true or false here
  end
end

Upvotes: 2

Related Questions