Skip to content

Instantly share code, notes, and snippets.

@chocoby
Created August 23, 2012 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chocoby/3436759 to your computer and use it in GitHub Desktop.
Save chocoby/3436759 to your computer and use it in GitHub Desktop.
Rails.cache でキャッシュがあればそのまま返す、なければキャッシュする
class Cache
#
# キャッシュが見つかったらそのまま返す
# 見つからなければブロック内の処理を実行し、キャッシュする
#
# ==== Options
#
# * key - キャッシュを取得するキー
# * options - write のオプション
#
# ==== Example
#
# Cache.find_or_cache('Miku', expires_in: 600) { 'Hatsune' }
# # => "Hatsune"
#
def self.find_or_cache(key, options = nil, &block)
cache = Rails.cache.read(key)
return cache unless cache.nil
data = block.call
Rails.cache.write(key, data, options)
data
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment