Created
August 23, 2012 13:47
-
-
Save chocoby/3436759 to your computer and use it in GitHub Desktop.
Rails.cache でキャッシュがあればそのまま返す、なければキャッシュする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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