Sha256: d62349354c0a99f8c80ed0c8c11f3723f2b0200a1e0e044ab31e5f17fd7d3b20

Contents?: true

Size: 1018 Bytes

Versions: 12

Compression:

Stored size: 1018 Bytes

Contents

module ActiveRecord
  module ShardFor
    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)
        @lock.synchronize { constantize! unless constantized? }

        model = @mapping.fetch(role_name)
        target_shard_model = model.shard_repository.fetch_by_key(from.assigned_key)

        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
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
activerecord-shard_for-0.7.0 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.6.1 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.6.0 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.5.0 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.4.1 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.4.0 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.3.0 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.2.1 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.2.0 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.1.2 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.1.1 lib/activerecord/shard_for/replication_mapping.rb
activerecord-shard_for-0.1.0 lib/activerecord/shard_for/replication_mapping.rb