Created
February 10, 2016 19:33
-
-
Save bmulvihill/26962fd5ffbc018ad9f1 to your computer and use it in GitHub Desktop.
cached methods
This file contains 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
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