Skip to content

Instantly share code, notes, and snippets.

@kreeger
Created March 11, 2013 17:54
Show Gist options
  • Select an option

  • Save kreeger/5136193 to your computer and use it in GitHub Desktop.

Select an option

Save kreeger/5136193 to your computer and use it in GitHub Desktop.
Smart caching, the intelligent way.
# 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
@kreeger

kreeger commented Mar 11, 2013

Copy link
Copy Markdown
Author

Call it as such.

class SomeClass
  include SmartFetch

  def do_something_intense(refresh=false)
    result = smart_fetch("some-cache-key", expires_in: 1.hour, force: refresh) do
      { some_crazy: 'hash-data' }
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment