Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache a value daily in rails?

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?

like image 651
Dr. Chocolate Avatar asked Jan 17 '26 02:01

Dr. Chocolate


1 Answers

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.

like image 103
infused Avatar answered Jan 19 '26 18:01

infused



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!