Skip to content

Instantly share code, notes, and snippets.

@shuuuuun
Created April 8, 2020 15:04
Show Gist options
  • Save shuuuuun/08566718ec1dc00573ba409463047b70 to your computer and use it in GitHub Desktop.
Save shuuuuun/08566718ec1dc00573ba409463047b70 to your computer and use it in GitHub Desktop.
# ref. https://railsguides.jp/caching_with_rails.html
# ref. https://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html
# write/read/fetch
Rails.cache.write('test_cache_key', Time.zone.now, expires_in: 10.seconds)
Rails.cache.read('test_cache_key', expires_in: 10.seconds)
Rails.cache.fetch('test_cache_key', expires_in: 10.seconds) { Time.zone.now }
class Model
def self.hoge
expires_in = Time.zone.now.end_of_day - Time.zone.now
cache_key = "Model.hoge/#{Time.zone.today}"
Rails.cache.fetch(cache_key, expires_in: expires_in, skip_nil: true) do
Time.zone.now
end
end
end
Model.hoge
# Clear cache
Rails.cache.clear
# $ bin/rails r 'Rails.cache.clear'
# Toggle development mode caching on/off
# $ bin/rails dev:cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment