Module: Switchman::ActiveRecord::Relation

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.prepended(klass) ⇒ Object



4
5
6
# File 'lib/switchman/active_record/relation.rb', line 4

def self.prepended(klass)
  klass::SINGLE_VALUE_METHODS.concat [ :shard, :shard_source ]
end

Instance Method Details

#activate(&block) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/switchman/active_record/relation.rb', line 79

def activate(&block)
  shards = all_shards
  if (Array === shards && shards.length == 1)
    if shards.first == DefaultShard || shards.first == Shard.current(klass.shard_category)
      yield(self, shards.first)
    else
      shards.first.activate(klass.shard_category) { yield(self, shards.first) }
    end
  else
    # TODO: implement local limit to avoid querying extra shards
    Shard.with_each_shard(shards, [klass.shard_category]) do
      shard(Shard.current(klass.shard_category), :to_a).activate(&block)
    end
  end
end

#cloneObject



14
15
16
17
18
# File 'lib/switchman/active_record/relation.rb', line 14

def clone
  result = super
  result.shard_value = Shard.current(klass ? klass.shard_category : :primary) unless shard_value
  result
end

#create(*args, &block) ⇒ Object



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

def create(*args, &block)
  primary_shard.activate(klass.shard_category) { super }
end

#create!(*args, &block) ⇒ Object



37
38
39
# File 'lib/switchman/active_record/relation.rb', line 37

def create!(*args, &block)
  primary_shard.activate(klass.shard_category) { super }
end

#explain(super_method: false) ⇒ Object



45
46
47
48
# File 'lib/switchman/active_record/relation.rb', line 45

def explain(super_method: false)
  return super() if super_method
  self.activate { |relation| relation.explain(super_method: true) }
end

#initialize(*args) ⇒ Object



8
9
10
11
12
# File 'lib/switchman/active_record/relation.rb', line 8

def initialize(*args)
  super
  self.shard_value = Shard.current(klass ? klass.shard_category : :primary) unless shard_value
  self.shard_source_value = :implicit unless shard_source_value
end

#merge(*args) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/switchman/active_record/relation.rb', line 20

def merge(*args)
  relation = super
  if relation.shard_value != self.shard_value && relation.shard_source_value == :implicit
    relation.shard_value = self.shard_value
    relation.shard_source_value = self.shard_source_value
  end
  relation
end

#new(*args, &block) ⇒ Object



29
30
31
# File 'lib/switchman/active_record/relation.rb', line 29

def new(*args, &block)
  primary_shard.activate(klass.shard_category) { super }
end

#to_sqlObject



41
42
43
# File 'lib/switchman/active_record/relation.rb', line 41

def to_sql
  primary_shard.activate(klass.shard_category) { super }
end