Sha256: a46a3596b33b683f5d8a6ec70d0bacebd2f6f82f642834681a6a95dc1bd68c22

Contents?: true

Size: 1.14 KB

Versions: 3

Compression:

Stored size: 1.14 KB

Contents

# -*- coding: utf-8 -*-
module ActiveRecord::Turntable::Algorithm
  class RangeAlgorithm < Base
    def initialize(config)
      @config = config
    end

    def calculate(key)
      idx = calculate_idx(key)
      @config[:shards][idx][:connection]
    rescue
      raise ActiveRecord::Turntable::CannotSpecifyShardError, "cannot specify shard for key:#{key}"
    end

    def calculate_idx(key)
      @config[:shards].find_index { |h| h[:less_than] > key }
    end

    # { connection_name => weight, ... }
    def calculate_used_shards_with_weight(sequence_value)
      current_shard_idx = calculate_idx(sequence_value)
      shards = @config[:shards][0..current_shard_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
      weighted_hash
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
activerecord-turntable-3.1.0 lib/active_record/turntable/algorithm/range_algorithm.rb
activerecord-turntable-3.0.1 lib/active_record/turntable/algorithm/range_algorithm.rb
activerecord-turntable-3.0.0 lib/active_record/turntable/algorithm/range_algorithm.rb