Skip to content

Instantly share code, notes, and snippets.

@bmulvihill
Created February 10, 2016 19:33
Show Gist options
  • Save bmulvihill/26962fd5ffbc018ad9f1 to your computer and use it in GitHub Desktop.
Save bmulvihill/26962fd5ffbc018ad9f1 to your computer and use it in GitHub Desktop.
cached methods
module Cacheable
def store
Rails.cache
end
def cache(*attributes)
attributes.each do |attribute|
if attribute.is_a?(Hash)
wrap(attribute.keys.first, attribute[attribute.keys.first])
else
wrap(attribute)
end
end
end
private
def wrap(method, options = {})
define_method("#{ method }_cache") do |*args|
self.class.store.fetch("#{ method }_#{ args.join('_') }", options) do
if args.empty?
send(method)
else
send(method, *args)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment