Sha256: 80cc87ef774aa82ddeb4dbc1eaa9cff763cf7081f61b4c18d5d84de3dd35b1fd

Contents?: true

Size: 1.26 KB

Versions: 2

Compression:

Stored size: 1.26 KB

Contents

module Dry
  module Web
    class Settings
      class FileParser
        # Regex extracted from dotenv gem
        # https://github.com/bkeepers/dotenv/blob/master/lib/dotenv/parser.rb#L14
        LINE = %r(
          \A
          \s*
          (?:export\s+)?    # optional export
          ([\w\.]+)         # key
          (?:\s*=\s*|:\s+?) # separator
          (                 # optional value begin
            '(?:\'|[^'])*'  #   single quoted value
            |               #   or
            "(?:\"|[^"])*"  #   double quoted value
            |               #   or
            [^#\n]+         #   unquoted value
          )?                # value end
          \s*
          (?:\#.*)?         # optional comment
          \z
        )x

        def call(file)
          File.readlines(file).each_with_object({}) do |line, hash|
            parse_line(line, hash)
          end
        rescue Errno::ENOENT
          {}
        end

        private

        def parse_line(line, hash)
          if (match = line.match(LINE))
            key, value = match.captures
            hash[key] = parse_value(value || "")
          end
          hash
        end

        def parse_value(value)
          value.strip.sub(/\A(['"])(.*)\1\z/, '\2')
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-web-0.7.1 lib/dry/web/settings/file_parser.rb
dry-web-0.7.0 lib/dry/web/settings/file_parser.rb