<commit_before>module ShardHandler
  class Handler
    def initialize(klass, configs)
      @klass = klass
      @configs = configs
      @cache = {}
    end

    def setup
      resolver = ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver.new(@configs)

      @configs.each do |name, _|
        name = name.to_sym

        connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
        connection_handler.establish_connection(@klass, resolver.spec(name))

        @cache[name] = connection_handler
      end
    end

    def connection_handler_for(name)
      return if name.nil?
      @cache.fetch(name.to_sym) do
        fail UnknownShardError, "#{name.inspect} is not a valid shard name"
      end
    end

    def disconnect_all
      @cache.values.map(&:clear_all_connections!)
    end
  end
end<commit_msg>Add documentation for Handler<commit_after>module ShardHandler
  # Handles which {ConnectionHandler} instance should be used based on the
  # shard name that is set for the Thread. Each {Model} class has its own
  # {Handler}.
  #
  # @see Model
  class Handler
    # @param klass [ActiveRecord::Base] model class
    # @param configs [Hash] a hash with database connection settings
    def initialize(klass, configs)
      @klass = klass
      @configs = configs
      @cache = {}
    end

    # Creates a {ConnectionHandler} instance for each configured shard and puts
    # it on cache to be used later by {#connection_handler_for}.
    def setup
      resolver = ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver.new(@configs)

      @configs.each do |name, _|
        name = name.to_sym

        connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
        connection_handler.establish_connection(@klass, resolver.spec(name))

        @cache[name] = connection_handler
      end
    end

    # Returns the appropriate ConnectionHandler instance for the given shard
    # name.
    #
    # @param name [Symbol, String] shard name
    def connection_handler_for(name)
      return if name.nil?
      @cache.fetch(name.to_sym) do
        fail UnknownShardError, "#{name.inspect} is not a valid shard name"
      end
    end

    # Disconnects from all shards.
    def disconnect_all
      @cache.values.map(&:clear_all_connections!)
    end
  end
end
{'fraction_non_alphanumeric': 0.08138048572645931, 'fraction_numerical': 0.0, 'mean_word_length': 3.0413080895008604, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5258960', 'n_tokens_mistral': 683, 'n_tokens_neox': 663, 'n_words': 190}