3

Whats the best way to cache a value daily in rails?

I have a database call that is accessible by an API and I want to make and store it on a daily basis.

What's the best way/practice to do this?

Dr. Chocolate
  • 2,043
  • 4
  • 25
  • 45

2 Answers2

8

Let's say you have a widget_price that you only want to update every 24 hours. Normally you use Widget.calculate_daily_price to get the daily price, but it takes too long to run slowing down your web pages.

widget_price = Widget.calculate_daily_price

Wrap that call with a Rails.cache.fetch and expire the results in 24 hours.

widget_price = Rails.cache.fetch('widget_price', expires_in: 24.hours) do
  Widget.calculate_daily_price
end

Now, if the widget_price is already cached that cached value will be used and the block will be ignored. If the cache has expired when this is run, the block will be executed and the cache set to the new value for another 24 hours.

infused
  • 24,000
  • 13
  • 68
  • 78
  • 1
    If it is a heavy query, then you'll probably want to also set the `race_condition_ttl` to avoid the dog pile effect. https://guides.rubyonrails.org/caching_with_rails.html#activesupport-cache-store – allen Jun 23 '21 at 14:29
0

I've another solution with https://github.com/igorkasyanchuk/rails_cached_method

You can simply change your code to Widget.cached.calculate_daily_price

and even specify expires_in: 24.hours if needed

Igor Kasyanchuk
  • 766
  • 6
  • 12