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
# 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|
    klass.alias_method_chain(method, :sharding)
  end
end

Instance Method Details

#association_scope_with_shardingObject



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

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

#build_record_with_sharding(*args) ⇒ Object



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

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

#creation_attributes_with_shardingObject



38
39
40
41
42
43
44
45
46
# File 'lib/switchman/active_record/association.rb', line 38

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



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

def load_target_with_sharding
  self.shard.activate { load_target_without_sharding }
end

#scope_with_shardingObject



33
34
35
36
# File 'lib/switchman/active_record/association.rb', line 33

def scope_with_sharding
  shard_value = @reflection.options[:multishard] ? @owner : self.shard
  @owner.shard.activate { scope_without_sharding.shard(shard_value, :association) }
end

#shardObject



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

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