Module: Switchman::ActiveRecord::Preloader::Association

Defined in:
lib/switchman/active_record/association.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



90
91
92
93
94
95
96
97
98
# File 'lib/switchman/active_record/association.rb', line 90

def self.included(klass)
  klass.send(:remove_method, :associated_records_by_owner)
  klass.send(:remove_method, :owners_by_key)
  if ::Rails.version < '4'
    klass.send(:remove_method, :scoped)
  else
    klass.send(:remove_method, :scope)
  end
end

Instance Method Details

#associated_records_by_owner(preloader = nil) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/switchman/active_record/association.rb', line 100

def associated_records_by_owner(preloader = nil)
  owners_map = owners_by_key

  if klass.nil? || owners_map.empty?
    records = []
  else
    # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000)
    # Make several smaller queries if necessary or make one query if the adapter supports it
    records = Shard.partition_by_shard(owners) do |partitioned_owners|
      sliced_owners = partitioned_owners.each_slice(model.connection.in_clause_length || partitioned_owners.size)
      sliced_owners.map do |slice|
        relative_owner_keys = slice.map do |owner|
          key = owner[owner_key_name]
          if key && owner.class.sharded_column?(owner_key_name)
            key = Shard.relative_id_for(key, owner.shard, Shard.current(owner.class.shard_category))
          end
          key && key.to_s
        end
        relative_owner_keys.compact!
        records_for(relative_owner_keys)
      end
    end
    records.flatten!
  end

  # Each record may have multiple owners, and vice-versa
  records_by_owner = owners.each_with_object({}) do |owner,h|
    h[owner] = []
  end
  records.each do |record|
    owner_key = record[association_key_name]
    owner_key = Shard.global_id_for(owner_key, record.shard) if owner_key && record.class.sharded_column?(association_key_name)

    owners_map[owner_key.to_s].each do |owner|
      records_by_owner[owner] << record
    end
  end
  records_by_owner
end

#owners_by_keyObject



140
141
142
143
144
145
146
# File 'lib/switchman/active_record/association.rb', line 140

def owners_by_key
  @owners_by_key ||= owners.group_by do |owner|
    key = owner[owner_key_name]
    key = Shard.global_id_for(key, owner.shard) if key && owner.class.sharded_column?(owner_key_name)
    key && key.to_s
  end
end

#scopeObject Also known as: scoped



148
149
150
# File 'lib/switchman/active_record/association.rb', line 148

def scope
  build_scope
end