Sha256: 06035b55560a620ce36832aee3ed70e941b93b73190945334426a0b0f944e529

Contents?: true

Size: 1.68 KB

Versions: 4

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

require 'pathname'

module Esse
  # Provides all configurations
  #
  # Example
  #   Esse.config do |conf|
  #     conf.indices_directory = 'app/indices'
  #   end
  class Config
    DEFAULT_CLUSTER_ID = :default
    ATTRIBUTES = %i[indices_directory].freeze

    # The location of the indices. Defaults to the `app/indices`
    attr_reader :indices_directory

    def initialize
      self.indices_directory = 'app/indices'
      @clusters = {}
      clusters(DEFAULT_CLUSTER_ID) # initialize the :default client
    end

    def cluster_ids
      @clusters.keys
    end

    def clusters(key = DEFAULT_CLUSTER_ID, **options)
      return unless key

      id = key.to_sym
      (@clusters[id] ||= Cluster.new(id: id)).tap do |c|
        c.assign(options) if options
        yield c if block_given?
      end
    end

    def indices_directory=(value)
      @indices_directory = value.is_a?(Pathname) ? value : Pathname.new(value)
    end

    def load(arg)
      case arg
      when Hash
        assign(arg)
      when File, Pathname
        # @TODO Load JSON or YAML
      when String
        # @TODO Load JSON or YAML if File.exist?(arg)
      else
        raise ArgumentError, printf('could not load configuration using: %p', val)
      end
    end

    private

    def assign(hash)
      hash.each do |key, value|
        method = (ATTRIBUTES & [key.to_s, key.to_sym]).first
        next unless method

        public_send("#{method}=", value)
      end
      if (connections = hash['clusters'] || hash[:clusters]).is_a?(Hash)
        connections.each do |key, value|
          clusters(key).assign(value) if value.is_a?(Hash)
        end
      end
      true
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
esse-0.0.5 lib/esse/config.rb
esse-0.0.4 lib/esse/config.rb
esse-0.0.3 lib/esse/config.rb
esse-0.0.2 lib/esse/config.rb