Created
August 24, 2012 21:09
-
-
Save barelyknown/3455643 to your computer and use it in GitHub Desktop.
Rails Cacheable Module
This file contains hidden or 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 | |
extend ActiveSupport::Concern | |
def cacheback(relationship) | |
if relationship.cacheable_attributes.any? | |
relationship.target_attributes.each do |target_attribute| | |
relationship.target.each { |member| member.send("calc_#{target_attribute}")} | |
end | |
relationship.target.each(&:save!) | |
end | |
end | |
class CacheRelationship | |
attr_accessor :target, :source, :attributes | |
def initialize(source, target, attributes, options={}) | |
self.source = source | |
self.target = target | |
self.attributes = attributes | |
end | |
def cacheable_attributes | |
@cacheable_attributes ||= calc_cacheable_attributes | |
end | |
def target_attributes | |
@target_attributes ||= calc_target_attributes | |
end | |
def calc_target_attributes | |
attributes.is_a?(Hash) ? cacheable_attributes.keys : cacheable_attributes | |
end | |
private :calc_target_attributes | |
def calc_cacheable_attributes | |
if attributes.is_a? Hash | |
attributes.select { |target_attribute, source_attribute| source.changed.include?(source_attribute.to_s) || source.destroyed? } | |
else | |
attributes | |
end | |
end | |
private :calc_cacheable_attributes | |
def target=(value) | |
@target = *source.send(value) | |
@target = @target.compact.each(&:reload) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment