public
Description: simple identity map for active record. eager loading associations FTL
Clone URL: git://github.com/technoweenie/active_record_context.git
Click here to lend your support to: active_record_context and make a donation at www.pledgie.com !
technoweenie (author)
Sat Nov 25 22:50:21 -0800 2006
active_record_context / lib / technoweenie / active_record_context.rb
100644 42 lines (36 sloc) 1.074 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
module Technoweenie
  module ActiveRecordContext
    def self.extended(base)
      class << base
        alias_method_chain :find_every, :context
        alias_method_chain :find_one, :context
      end
    end
    
    mattr_reader :context_cache
 
    def find_every_with_context(options)
      returning find_every_without_context(options) do |records|
        store_in_context records
      end
    end
    
    def find_one_with_context(id, options)
      cached = options[:conditions].nil? && find_in_context(id)
      cached ? cached : find_one_without_context(id, options)
    end
 
    def find_in_context(id)
      context_cache && context_cache[self] && context_cache[self][id.to_i]
    end
    
    def store_in_context(records)
      return if context_cache.nil?
      records.inject(context_cache[self] ||= {}) do |memo, record|
        memo.update record.id => record
      end
    end
    
    # Enables the context cache inside this block.
    def with_context
      @@context_cache = {}
      yield
    ensure
      @@context_cache = nil
    end
  end
end