Sha256: 397f666227b7cafb3a46b99d14dd25f20d64c702978e26c0c5a1652fe3b4a934

Contents?: true

Size: 1.08 KB

Versions: 3

Compression:

Stored size: 1.08 KB

Contents

require "easy-settings/coercion"

class EasySettings::PathSource
  attr_reader :base_path, :separator, :converter, :parse_values

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

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

        variable = path.gsub("#{base_path}/", "")
        value = File.read(path).strip

        keys = variable.to_s.split(separator)
        assign_value(data, keys, value)
      end
    end
  end

  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
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
easy-settings-1.3.1 lib/easy-settings/path_source.rb
easy-settings-1.3.0 lib/easy-settings/path_source.rb
easy-settings-1.2.0 lib/easy-settings/path_source.rb