Vlad Hilko
Vlad Hilko

Reputation: 1244

What is the best way for caching database query for the Service Object inside the iterations?

I have a rails Service Object - CarChecker and model AvailableCar:

class CarChecker
  def car_is_available?(car)
    list_of_available_cars.include?(car)
  end

  def list_of_available_cars
    AvailableCar.all.map { ... }
  end
end

Then I check every car somewhere in controller

cars.each do |car|
  CarChecker.new().car_is_available?(car)
end

How can I avoid of sending request AvailableCar.all for every iteration and send it only once? What is the best way for caching such kind of behavior?

Upvotes: 0

Views: 35

Answers (1)

khelwood
khelwood

Reputation: 59146

You often see methods assigning to instance variables for caching like this.

def list_of_available_cars
  @allcars ||= AvailableCar.all.map { ... }
end

The first time list_of_available_cars is called, AvailableCars.all... will be executed, and the result stored in an instance variable. Subsequent times, the stored value will be returned.

For it to work this way, you would need to be reusing the same instance of the service class.

checker = CarChecker.new
cars.each do |car|
  checker.car_is_available?(car)
end

If you must use a new instance of CarChecker each time, then you can use a class variable instead of an instance variable (i.e. use @@ instead of @):

def list_of_available_cars
  @@allcars ||= AvailableCar.all.map { ... }
end

As long as your AvailableCar.all.map { ... } is always going to return the same result, that should be fine.

Upvotes: 1

Related Questions