Sha256: c3cde0b3bdaf9a110544638f81ae77300b5daff4a32fe67c59a116b4772d50ea

Contents?: true

Size: 1.91 KB

Versions: 3

Compression:

Stored size: 1.91 KB

Contents

# encoding: utf-8
module LocalPac

  class Config
    private

    attr_reader :config

    @options = []
    class << self

      attr_reader :options

      def option(option, default_value)
        define_method option.to_sym do
          config.fetch(option.to_sym, default_value)
        end

        @options << option
      end
    end

    public

    def initialize(file = available_config_file, config_engine = Psych)
      config_mutex = Mutex.new
      config_mutex.synchronize do
        yaml = Psych.load_file(file)

        if yaml.respond_to? :[]
          @config = yaml.symbolize_keys.freeze
        else
          @config = {}.freeze
        end
      end
    rescue => e
      fail Exceptions::ConfigFileNotReadable, "Sorry, but there was a problem reading the config file: #{e.message}."
    end

    option :log_sink, File.join(ENV['HOME'], '.local', 'share', 'local_pac', 'log')
    option :local_storage, File.join(ENV['HOME'], '.local', 'share', 'local_pac', 'data')
    option :executable, File.expand_path('../../../bin/local_pac', __FILE__)
    option :pid_file, File.join(ENV['HOME'], '.local', 'share', 'local_pac', 'run', 'pid')
    option :gem_path, Gem.path

    def to_s
      result = []
      result << sprintf("%20s | %s", 'option', 'value')
      result << sprintf("%s + %s", '-' * 20, '-' * 80)

      Config.options.each do |o|
        result << sprintf("%20s | %s", o, Array(public_send(o)).join(', '))
      end

      result.join("\n")
    end

    private

    def candiate_files
      [
        File.expand_path(File.join(ENV['HOME'], '.config', 'local_pac', 'config.yaml')),
        File.expand_path(File.join(ENV['HOME'], '.local_pac', 'config.yaml')),
        File.expand_path(File.join('/etc', 'local_pac', 'config.yaml')),
        File.expand_path('../../../files/config.yaml', __FILE__),
      ]
    end

    def available_config_file
      candiate_files.find { |f| File.exists? f }
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
local_pac-0.1.10 lib/local_pac/config.rb
local_pac-0.1.9 lib/local_pac/config.rb
local_pac-0.1.8 lib/local_pac/config.rb