Class: ActiveRecord::Turntable::Algorithm::RangeAlgorithm
- Defined in:
- lib/active_record/turntable/algorithm/range_algorithm.rb
Instance Method Summary collapse
- #calculate(key) ⇒ Object
- #calculate_idx(key) ⇒ Object
-
#calculate_used_shards_with_weight(sequence_value) ⇒ Object
{ connection_name => weight, … }.
-
#initialize(config) ⇒ RangeAlgorithm
constructor
A new instance of RangeAlgorithm.
Constructor Details
#initialize(config) ⇒ RangeAlgorithm
Returns a new instance of RangeAlgorithm.
4 5 6 |
# File 'lib/active_record/turntable/algorithm/range_algorithm.rb', line 4 def initialize(config) @config = config end |
Instance Method Details
#calculate(key) ⇒ Object
8 9 10 11 12 13 |
# File 'lib/active_record/turntable/algorithm/range_algorithm.rb', line 8 def calculate(key) idx = calculate_idx(key) @config["shards"][idx]["connection"] rescue raise ActiveRecord::Turntable::CannotSpecifyShardError, "cannot specify shard for key:#{key}" end |
#calculate_idx(key) ⇒ Object
15 16 17 |
# File 'lib/active_record/turntable/algorithm/range_algorithm.rb', line 15 def calculate_idx(key) @config["shards"].find_index {|h| h["less_than"] > key } end |
#calculate_used_shards_with_weight(sequence_value) ⇒ Object
{ connection_name => weight, … }
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/active_record/turntable/algorithm/range_algorithm.rb', line 20 def calculate_used_shards_with_weight(sequence_value) idx = calculate_idx(sequence_value) last_connection = calculate(sequence_value) shards = @config["shards"][0..idx] weighted_hash = Hash.new {|h,k| h[k]=0} prev_max = 0 shards.each_with_index do |h,idx| weighted_hash[h["connection"]] += if idx < shards.size - 1 h["less_than"] - prev_max - 1 else sequence_value - prev_max end prev_max = h["less_than"] - 1 end return weighted_hash end |