Module: Switchman::ActiveRecord::Association

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



4
5
6
7
8
9
# File 'lib/switchman/active_record/association.rb', line 4

def self.included(klass)
  %w{build_record creation_attributes load_target association_scope scope}.each do |method|
    method = 'scoped' if method == 'scope' && ::Rails.version < '4'
    klass.alias_method_chain(method, :sharding)
  end
end

Instance Method Details

#association_scope_with_shardingObject



28
29
30
31
32
# File 'lib/switchman/active_record/association.rb', line 28

def association_scope_with_sharding
  if klass
    shard.activate(klass.shard_category) { association_scope_without_sharding }
  end
end

#build_record_with_sharding(*args) ⇒ Object



20
21
22
# File 'lib/switchman/active_record/association.rb', line 20

def build_record_with_sharding(*args)
  self.shard.activate { build_record_without_sharding(*args) }
end

#creation_attributes_with_shardingObject



43
44
45
46
47
48
49
50
51
# File 'lib/switchman/active_record/association.rb', line 43

def creation_attributes_with_sharding
  attributes = creation_attributes_without_sharding

  # translate keys
  if reflection.macro.in?([:has_one, :has_many]) && !options[:through]
    attributes[reflection.foreign_key] = Shard.relative_id_for(owner[reflection.active_record_primary_key], owner.shard, self.shard)
  end
  attributes
end

#load_target_with_shardingObject



24
25
26
# File 'lib/switchman/active_record/association.rb', line 24

def load_target_with_sharding
  self.shard.activate { load_target_without_sharding }
end

#shardObject



11
12
13
14
15
16
17
18
# File 'lib/switchman/active_record/association.rb', line 11

def shard
  if @reflection.options[:polymorphic] || @reflection.klass.shard_category == @owner.class.shard_category
    # polymorphic associations assume the same shard as the owning item
    @owner.shard
  else
    Shard.default
  end
end