Sha256: 678ed8546e7a94b484676b31a5bfbaaf4b9a8d908461902d4f05fcde5be33819

Contents?: true

Size: 1.39 KB

Versions: 1

Compression:

Stored size: 1.39 KB

Contents

module ActiveRecord
  module ShardFor
    class ShardRepogitory < AbstractShardRepository
      attr_reader :base_class

      # @param [ClusterConfig] cluster_config
      # @param [Class] base_class A AR Model
      def initialize(cluster_config, base_class)
        @base_class = base_class

        @shards = cluster_config.connection_registry.each_with_object({}) do |(key, connection_name), hash|
          model = generate_model_for_shard(connection_name, key)
          base_class.const_set(:"#{generate_class_name(connection_name)}", model)
          hash[connection_name] = model
        end
      end

      private

      # @param [Symbol] connection_name
      # @param [Range] slot_range
      # @return [Class] A sub class of given AR model.
      #   A sub class has connection setting for specific shard.
      def generate_model_for_shard(connection_name, key)
        class_name = generate_class_name(connection_name)

        model = Class.new(base_class) do
          self.table_name = base_class.table_name
          class << self
            attr_reader :assigned_key
          end
          @assigned_key = key

          module_eval <<-RUBY, __FILE__, __LINE__ + 1
            def self.name
              "#{base_class.name}::#{class_name}"
            end
          RUBY
        end

        model.class_eval { establish_connection(connection_name) }
        model
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord-shard_for-0.5.0 lib/activerecord/shard_for/shard_repogitory.rb