Sha256: f272a998d55bdb64e198a6a7441bed713bd38fa4725d0591f390c78cf9107fa8

Contents?: true

Size: 949 Bytes

Versions: 3

Compression:

Stored size: 949 Bytes

Contents

module MixedGauge
  class ReplicationMapping
    def initialize(mapping)
      @mapping = mapping
      @lock = Mutex.new
    end

    # @param [Class] A shard model having connection to specific shard
    # @param [Symbol] A role name of target cluster.
    # @return [Class, Object] if block given then yielded result else
    #   target shard model.
    def switch(from, role_name, &block)
      @lock.synchronize { constantize! unless constantized? }

      model = @mapping.fetch(role_name)
      target_shard_model = model.shard_repository.fetch_by_slots(from.assigned_slots)

      if block_given?
        target_shard_model.connection_pool.with_connection { yield target_shard_model }
      else
        target_shard_model
      end
    end

    private

    def constantize!
      @mapping = Hash[@mapping.map {|k, name| [k, name.to_s.constantize] }]
    end

    def constantized?
      @mapping.values.first.is_a? Class
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mixed_gauge-1.2.0.beta2 lib/mixed_gauge/replication_mapping.rb
mixed_gauge-1.2.0.beta1 lib/mixed_gauge/replication_mapping.rb
mixed_gauge-1.1.0 lib/mixed_gauge/replication_mapping.rb