aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/identity_map.rb
blob: 79eb4dd83a5d763397bb8174a973f6733e189436 (plain) (blame)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
module ActiveRecord
  module IdentityMap
    extend ActiveSupport::Concern

    class << self
      attr_accessor :repositories
      attr_accessor :current_repository_name
      attr_accessor :enabled

      def current
        repositories[current_repository_name] ||= Weakling::WeakHash.new
      end

      def with_repository(name = :default, &block)
        old_repository = self.current_repository_name
        self.current_repository_name = name

        block.call(current)
      ensure
        self.current_repository_name = old_repository
      end

      def without(&block)
        old, self.enabled = self.enabled, false

        block.call
      ensure
        self.enabled = old
      end

      def get(class_name, primary_key)
        current[[class_name, primary_key]]
      end

      def add(record)
        current[[record.class.name, record.id]] = record
      end

      def remove(record)
        current.delete([record.class.name, record.id])
      end

      def clear
        current.clear
      end

      alias enabled? enabled
    end

    self.repositories ||= Hash.new
    self.current_repository_name ||= :default
    self.enabled = true

    module InstanceMethods

    end

    module ClassMethods
      def identity_map
        ActiveRecord::IdentityMap
      end
    end
  end
end