Skip to content

Instantly share code, notes, and snippets.

@jugyo
Created March 2, 2012 04:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jugyo/1955798 to your computer and use it in GitHub Desktop.
Save jugyo/1955798 to your computer and use it in GitHub Desktop.
memoize with memcache store in Rails
# Usage:
#
# module ApplicationHelper
# extend MemcacheMemoize
#
# def bar(count = 10)
# "BAR" * count
# end
# memcache_memoize :bar, :expires_in => 10
# end
#
module MemcacheMemoize
def memcache_memoize(method, options)
define_method(:"#{method}_with_memcache_memoize") do |*args|
key = Digest::SHA1.hexdigest("#{self.class.name}##{method}(#{args.map(&:to_s).join(',')})")
Rails.cache.fetch(key, options) { __send__(:"#{method}_without_memcache_memoize", *args) }
end
alias_method_chain method, :memcache_memoize
end
end
@joshuapinter
Copy link

I've wanted to create this for some time. Glad you posted it and that I found it.

@joshuapinter
Copy link

Question:

  1. Why the hexdigest? Is that more efficient?

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