Skip to content

Instantly share code, notes, and snippets.

@morr
Created March 26, 2014 09:25
Show Gist options
  • Save morr/9779567 to your computer and use it in GitHub Desktop.
Save morr/9779567 to your computer and use it in GitHub Desktop.
module ActiveCacher
def self.prepended target
cacher = self
target.send :define_singleton_method, :rails_cache do |*methods|
methods.each do |method|
escaped_method = method.to_s.include?('?') ? "is_#{method[0..-2]}" : method
cacher.send :define_method, method do |*args|
instance_variable_get("@#{escaped_method}") ||
instance_variable_set("@#{escaped_method}", Rails.cache.fetch([cache_key_object, method], expires_in: 2.weeks) { prepare_for_cache(super *args) })
end
end
end
target.send :define_singleton_method, :instance_cache do |*methods|
methods.each do |method|
escaped_method = method.to_s.include?('?') ? "is_#{method[0..-2]}" : method
cacher.send :define_method, method do |*args|
instance_variable_get("@#{escaped_method}") ||
instance_variable_set("@#{escaped_method}", prepare_for_cache(super *args))
end
end
end
end
private
def cache_key_object
respond_to?(:object) ? object : self
end
def prepare_for_cache object
object.kind_of?(ActiveRecord::Relation) ? object.to_a : object
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment