Module: IdentityCache::BelongsToCaching::ClassMethods

Defined in:
lib/belongs_to_caching.rb

Instance Method Summary collapse

Instance Method Details

#build_normalized_belongs_to_cache(association, options) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/belongs_to_caching.rb', line 26

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

#cache_belongs_to(association, options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/belongs_to_caching.rb', line 10

def cache_belongs_to(association, options = {})
  self.cached_belongs_tos ||= {}
  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[:associated_class] ||= reflect_on_association(association).class_name

  if options[:embed]
    raise NotImplementedError
  else
    build_normalized_belongs_to_cache(association, options)
  end
end