Sha256: a3fa4bd22803b8b13dc3a74974d8666d3f51f2c277dacdfe062da919baee5a87

Contents?: true

Size: 1.62 KB

Versions: 13

Compression:

Stored size: 1.62 KB

Contents

# encoding: utf-8

require "singleton"
require "yaml"
require "pathname"

module Desi

  class Configuration
    include Singleton

    attr_reader :directory

    def directory=(dir)
      @directory = Pathname(File.expand_path(dir))
    end

    attr_accessor :server

    def load_configuration!
      config = defaults.merge(config_files_data)

      public_methods(false).select {|m| m.to_s =~ /=$/ }.each do |setter|
        attr_name = setter.to_s.tr('=', '')

        if config.has_key?(attr_name)
          send(setter, config[attr_name])
        end
      end

      self
    end

    private

    def config_files
      %w[/etc/desi.yml ~/.desi.yml]
    end

    def config_files_data
      config_files.each_with_object({}) do |filename, hash|
        hash.merge! config_file_data(filename)
      end
    end

    def config_file_data(filename)
      file = File.expand_path(filename)
      return {} unless File.exists?(file)

      data = YAML.load_file(file)

      if data.is_a? Hash
        data
      else
        warn "Configuration file #{filename} contains malformed data and will be ignored"
        {}
      end
    end

    def defaults
      {'directory' => "~/elasticsearch", "server" => "localhost:9200"}
    end

    instance.load_configuration!
  end # Configuration

  module_function


  # Change configuration settings
  #
  # @example
  #
  # Desi.configure do |c|
  #   c.directory = "~/es"
  #   c.server = "127.0.0.53:9200"
  # end
  #
  # @return [Desi::Configuration] the configuration
  def configure(&block)
    yield configuration
    configuration
  end

  def configuration
    Configuration.instance
  end

end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
desi-0.7.2 lib/desi/configuration.rb
desi-0.7.1 lib/desi/configuration.rb
desi-0.7.0 lib/desi/configuration.rb
desi-0.6.9 lib/desi/configuration.rb
desi-0.6.8 lib/desi/configuration.rb
desi-0.6.7 lib/desi/configuration.rb
desi-0.6.6 lib/desi/configuration.rb
desi-0.6.5 lib/desi/configuration.rb
desi-0.6.4 lib/desi/configuration.rb
desi-0.6.2 lib/desi/configuration.rb
desi-0.6.1 lib/desi/configuration.rb
desi-0.6.0 lib/desi/configuration.rb
desi-0.5.0 lib/desi/configuration.rb