How do I cache a value daily in rails?

What's the best way to cache the value daily in rails?

I have a database call available API and I want to create and store it daily.

What's the best way / practice for this?

+3


source to share


1 answer


Let's say you have widget_price

one that you want to update every 24 hours. You usually use Widget.calculate_daily_price

to get the daily price, but it takes too long to slow down your web pages.

widget_price = Widget.calculate_daily_price

      

Wrap this call with Rails.cache.fetch and complete the results in 24 hours.



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

      

Now, if widget_price is already cached, the cached value will be used and the block will be ignored. If the cache expired while it is running, the block will be executed and the cache will be set to a new value for another 24 hours.

+3


source







All Articles