Class: ActiveRecordShards::ShardSelection

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_shards/shard_selection.rb

Constant Summary collapse

NO_SHARD =
:_no_shard
PRIMARY =
"primary"

Instance Method Summary collapse

Constructor Details

#initializeShardSelection

Returns a new instance of ShardSelection.



8
9
10
11
# File 'lib/active_record_shards/shard_selection.rb', line 8

def initialize
  @on_replica = false
  @shard = nil
end

Instance Method Details

#on_replica=(new_replica) ⇒ Object



50
51
52
# File 'lib/active_record_shards/shard_selection.rb', line 50

def on_replica=(new_replica)
  @on_replica = (new_replica == true)
end

#on_replica?Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/active_record_shards/shard_selection.rb', line 46

def on_replica?
  @on_replica
end

#optionsObject



54
55
56
# File 'lib/active_record_shards/shard_selection.rb', line 54

def options
  { shard: @shard, replica: @on_replica }
end

#resolve_connection_name(sharded:, configurations:) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/active_record_shards/shard_selection.rb', line 22

def resolve_connection_name(sharded:, configurations:)
  resolved_shard = sharded ? shard : nil
  env = ActiveRecordShards.app_env

  @connection_names ||= {}
  @connection_names[env] ||= {}
  @connection_names[env][resolved_shard] ||= {}
  @connection_names[env][resolved_shard][@on_replica] ||= begin
    name = env.dup
    name << "_shard_#{resolved_shard}" if resolved_shard
    if @on_replica && configurations["#{name}_replica"]
      "#{name}_replica"
    else
      # ActiveRecord always names its default connection pool 'primary'
      # while everything else is named by the configuration name
      resolved_shard ? name : PRIMARY
    end
  end
end

#shardObject



13
14
15
16
17
18
19
# File 'lib/active_record_shards/shard_selection.rb', line 13

def shard
  if @shard.nil? || @shard == NO_SHARD
    nil
  else
    @shard || self.class.default_shard
  end
end

#shard=(new_shard) ⇒ Object



42
43
44
# File 'lib/active_record_shards/shard_selection.rb', line 42

def shard=(new_shard)
  @shard = (new_shard || NO_SHARD)
end