Sha256: 3cdb267e021205ee3bc156314ab89ce6d7b3607812eddf421fec7037bc3e7906

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

require 'pg/dsn_parser/version'
require 'strscan'

module PG
  class DSNParser
    def self.parse(*args)
      new.parse(*args)
    end

    def parse(dsn)
      scanner = StringScanner.new(dsn)

      dsn_hash = {}

      until scanner.eos?
        # get the key by matching up to and including the (optionally) white space bordered '='
        key = scanner.scan_until(/\s?=\s?/)
        key = key[0...-scanner.matched_size]

        dsn_hash[key.to_sym] = get_dsn_value(scanner)
      end

      dsn_hash
    end

    private

    def get_dsn_value(scanner)
      value =
        if scanner.peek(1) == "'"
          # if we are a quoted value get the first quote and the
          # string that ends with a quote not preceded by a backslash
          scanner.getch + scanner.scan_until(/(?<!\\)'\s*/).strip
        else
          scanner.scan_until(/\s+|$/).strip
        end

      value = value[1..-2] if value.start_with?("'") && value.end_with?("'")

      # un-escape any single quotes in the remaining value
      value.gsub(/\\'/, "'")
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pg-dsn_parser-0.1.0 lib/pg/dsn_parser.rb