Class: LocalPac::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/local_pac/config.rb

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = available_config_file, config_engine = Psych) ⇒ Config

Returns a new instance of Config.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/local_pac/config.rb', line 41

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
    else
      @config = {}
    end
  end
rescue StandardError => e
  fail Exceptions::ConfigFileNotReadable, JSON.dump(message: e.message, file: file)
end

Class Attribute Details

.optionsObject (readonly)

Returns the value of attribute options.



15
16
17
# File 'lib/local_pac/config.rb', line 15

def options
  @options
end

Class Method Details

.option(option, default_value) ⇒ Object



33
34
35
36
# File 'lib/local_pac/config.rb', line 33

def option(option, default_value)
  option_reader(option, default_value)
  option_writer(option)
end

.option_reader(option, default_value) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/local_pac/config.rb', line 17

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

  @options << option
end

.option_writer(option) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/local_pac/config.rb', line 25

def option_writer(option)
  define_method "#{option}=".to_sym do |value|
    config[option.to_sym] = value
  end

  @options << option
end

Instance Method Details

#allowed_config_file_pathsObject



88
89
90
91
92
93
94
95
# File 'lib/local_pac/config.rb', line 88

def allowed_config_file_paths
  [
    ::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

#lockObject



56
57
58
# File 'lib/local_pac/config.rb', line 56

def lock
  config.freeze
end

#to_sObject



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/local_pac/config.rb', line 76

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