Module: Ohm::IdentityMap

Defined in:
lib/ohm/identity_map.rb

Defined Under Namespace

Modules: Macros

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.included(model) ⇒ Object



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
43
44
45
46
47
# File 'lib/ohm/identity_map.rb', line 6

def self.included(model)
  model.extend(Macros)

  class << model
    alias original_loader []

    def [](id)
      if map = Thread.current[:_ohm_identity_map]
        key = self.key[id]

        map.fetch(key) { map.store(key, original_loader(id)) }
      else
        original_loader(id)
      end
    end

    alias original_fetch fetch

    def fetch(ids)
      if map = Thread.current[:_ohm_identity_map]
        missing_ids, missing_indices = [], []

        mapped = ids.map.with_index do |id, index|
          map.fetch(self.key[id]) do
            missing_ids << id
            missing_indices << index
            nil
          end
        end

        original_fetch(missing_ids).each.with_index do |instance, index|
          mapped[missing_indices[index]] = instance
          map.store(self.key[missing_ids[index]], instance)
        end

        mapped
      else
        original_fetch(ids)
      end
    end
  end
end