Sha256: 980a2f886f8a5cd2dfcc78d35fd0eb7b7744dda27b82996e955392b36c712fe7

Contents?: true

Size: 1.46 KB

Versions: 3

Compression:

Stored size: 1.46 KB

Contents

module IdentityCache
  module BelongsToCaching
    extend ActiveSupport::Concern

    included do |base|
      base.class_attribute :cached_belongs_tos
      base.cached_belongs_tos = {}
    end

    module ClassMethods
      def cache_belongs_to(association, options = {})
        self.cached_belongs_tos[association] = options

        options[:embed] ||= false
        options[:cached_accessor_name]    ||= "fetch_#{association}"
        options[:foreign_key]             ||= reflect_on_association(association).foreign_key
        options[:association_class]       ||= reflect_on_association(association).klass
        options[:prepopulate_method_name] ||= "prepopulate_fetched_#{association}"
        if options[:embed]
          raise NotImplementedError
        else
          build_normalized_belongs_to_cache(association, options)
        end
      end

      def build_normalized_belongs_to_cache(association, options)
        self.class_eval(<<-CODE, __FILE__, __LINE__ + 1)
          def #{options[:cached_accessor_name]}
            if IdentityCache.should_cache? && #{options[:foreign_key]}.present? && !association(:#{association}).loaded?
              self.#{association} = #{options[:association_class]}.fetch_by_id(#{options[:foreign_key]})
            else
              #{association}
            end
          end

          def #{options[:prepopulate_method_name]}(record)
            self.#{association} = record
          end
        CODE
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
identity_cache-0.2.1 lib/identity_cache/belongs_to_caching.rb
identity_cache-0.2.0 lib/identity_cache/belongs_to_caching.rb
identity_cache-0.1.0 lib/identity_cache/belongs_to_caching.rb