Sha256: 3e2f82d8da1b376ec4f21a84166e2a587c314c6f05b73d844ae55998a7a793a5

Contents?: true

Size: 810 Bytes

Versions: 6

Compression:

Stored size: 810 Bytes

Contents

# Scans for occurrences of a key in a line of text and returns any associated
# values.
#
# Looks for the following patterns of key-value pairs:
# KEY=value
# KEY='value'
# KEY="value"
# KEY value
# KEY 'value'
# KEY "value"
# KEY: value
# KEY => value
class Carwash::ValueDiscoverer < Struct.new(:key)
  def discover(line)
    patterns.flat_map { |pattern|
      line.scan(pattern).map(&:first)
    }.reject(&:nil?).reject(&:empty?).map(&:downcase).map { |val|
      unescape_value(val)
    }
  end

  def patterns
    @patterns ||= [
      %r{#{key}['"]?\s*(?:=>|=|:|\s+)\s*'((?:\\'|[^'])+)'}i,
      %r{#{key}['"]?\s*(?:=>|=|:|\s+)\s*"((?:\\"|[^"])+)"}i,
      %r{#{key}['"]?\s*(?:=>|=|:|\s+)\s*((?:\\\s|\\"|\\'|[^\s'"])+)}i
    ]
  end

  def unescape_value(value)
    value.gsub(/\\(.)/) { $1 }
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
carwash-1.0.5 lib/carwash/value_discoverer.rb
carwash-1.0.4 lib/carwash/value_discoverer.rb
carwash-1.0.3 lib/carwash/value_discoverer.rb
carwash-1.0.2 lib/carwash/value_discoverer.rb
carwash-1.0.1 lib/carwash/value_discoverer.rb
carwash-1.0.0 lib/carwash/value_discoverer.rb