Class: EasySettings::PathSource

Inherits:
Object
  • Object
show all
Defined in:
lib/easy-settings/path_source.rb

Direct Known Subclasses

CertificateManagerSource, EnvSource

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_path, settings_root: [], separator: "__", converter: :downcase, parse_values: true) ⇒ PathSource

Returns a new instance of PathSource.



6
7
8
9
10
11
12
# File 'lib/easy-settings/path_source.rb', line 6

def initialize(base_path, settings_root: [], separator: "__", converter: :downcase, parse_values: true)
  @base_path = base_path.to_s
  @settings_root = settings_root
  @separator = separator
  @converter = converter
  @parse_values = parse_values
end

Instance Attribute Details

#base_pathObject (readonly)

Returns the value of attribute base_path.



4
5
6
# File 'lib/easy-settings/path_source.rb', line 4

def base_path
  @base_path
end

#converterObject (readonly)

Returns the value of attribute converter.



4
5
6
# File 'lib/easy-settings/path_source.rb', line 4

def converter
  @converter
end

#parse_valuesObject (readonly)

Returns the value of attribute parse_values.



4
5
6
# File 'lib/easy-settings/path_source.rb', line 4

def parse_values
  @parse_values
end

#separatorObject (readonly)

Returns the value of attribute separator.



4
5
6
# File 'lib/easy-settings/path_source.rb', line 4

def separator
  @separator
end

#settings_rootObject (readonly)

Returns the value of attribute settings_root.



4
5
6
# File 'lib/easy-settings/path_source.rb', line 4

def settings_root
  @settings_root
end

Instance Method Details

#assign_value(data, keys, value) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/easy-settings/path_source.rb', line 27

def assign_value(data, keys, value)
  keys.map! do |key|
    next key.to_i if key =~ /^\d+/
    next key.send(converter) if converter
    key
  rescue NoMethodError => e
    raise "Invalid name converter: #{converter}"
  end

  leaf = keys[0...-1].each_with_index.inject(data){ |h, (key, i)| h[key] ||= keys[i + 1].is_a?(Integer) ? [] : {} }
  leaf[keys.last] = parse_values ? EasySettings::Coercion.new(value).run : value
end

#loadObject



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/easy-settings/path_source.rb', line 14

def load
  {}.tap do |data|
    Dir["#{base_path}/*"].each do |path|
      next unless File.file?(path)

      variable = path.gsub("#{base_path}/", "")
      keys = settings_root + variable.to_s.split(separator)
      value = File.binread(path).strip
      assign_value(data, keys, value)
    end
  end
end