Created
March 11, 2013 17:54
-
-
Save kreeger/5136193 to your computer and use it in GitHub Desktop.
Smart caching, the intelligent way.
This file contains hidden or 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
| # Contains better caching retrieval and storage logic. | |
| module SmartFetch | |
| # Intelligently caches the block if needed, or retrieves it from cache. | |
| # @param [String] name the name of the cache key. | |
| # @param [Hash] options options to feed to a call to `Rails.cache.write`, if required. | |
| # @param [Block] blk anything inside of this block gets cached. | |
| # @return [String] the contents of the cache. | |
| def smart_fetch(name, options={}, &blk) | |
| unless options[:force] | |
| in_cache = Rails.cache.fetch(name) | |
| return in_cache if in_cache | |
| end | |
| val = yield | |
| Rails.cache.write(name, val, options) unless val.nil? | |
| return val | |
| end | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Call it as such.