Skip to content

Instantly share code, notes, and snippets.

@jgn
Created February 3, 2011 19:34
Show Gist options
  • Select an option

  • Save jgn/810023 to your computer and use it in GitHub Desktop.

Select an option

Save jgn/810023 to your computer and use it in GitHub Desktop.
Memoization to memcache
# Memcache wrapping in a declarative fashion.
#
# Usage example:
#
# class << self
# extend Utils::MemoizableWithMC
#
# def get_host_details(id)
# select('host_first_name, host_last_name, host_email').find(id)
# end
# memoize_with_mc :get_host_details, :expires_in => 10
#
# end
#
# Limitations:
# - The MC key uses arg.inspect
# - For the MC options (like :expires_in => 10), it must be possible to
# inspect and then eval the object, and get a copy of the original object.
#
module Utils
module MemoizableWithMC
def self.wrapper(key, options = {})
Rails.cache.fetch(key, options) { yield }
end
def memoize_with_mc(symbol, options = {})
original_method = :"_unmemoized_with_mc_#{symbol}"
class_eval <<-EOS, __FILE__, __LINE__ + 1
alias #{original_method} #{symbol}
define_method(symbol) do |arg|
MemoizableWithMC::wrapper("MWMC:#{symbol}:" + arg.inspect, eval("#{options.inspect}")) do
#{original_method}(arg)
end
end
EOS
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment