Reputation: 2165
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?
Upvotes: 3
Views: 1427
Reputation: 774
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
Upvotes: 0
Reputation: 24337
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.
Upvotes: 8