module JavaProperties::Parsing::Parser

This module allows parsing of a properties file content string into a {Properties} object

@example

Parser.parse("item=something \u05d4") => {:item => "something ה"}

Constants

KEY_ESCAPE

Symbol which escapes a KEY_VALUE_MARKER in the key name @return [String]

KEY_ONLY_MARKER

Marker for a line which only consists of an key w/o value @return [Regexp]

KEY_VALUE_MARKER

Symbol which separates key from value after normalization @return [String]

Public Class Methods

parse(text) click to toggle source

Parses a string into a {Properties} object @param text [String] @return [Properties]

# File lib/java-properties/parsing/parser.rb, line 27
def self.parse(text)
  properties = Properties.new
  Normalizer.normalize!(text)
  text.each_line do |line|
    key, value = extract_key_and_value(line.chomp)
    append_to_properties(properties, key, value)
  end
  properties
end

Private Class Methods

append_to_properties(properties, key, value) click to toggle source
# File lib/java-properties/parsing/parser.rb, line 56
def self.append_to_properties(properties, key, value)
  return if key.nil? || value.nil?

  keys = key.split(".").map { |k| Encoding.decode!(k) }
  current_nest = properties
  while k = keys.shift
    if keys.size == 0
      current_nest[k] = Encoding.decode!(value, Encoding::SKIP_SEPARATORS)
    else
      if !current_nest.has_key? k
        current_nest[k] = {}
      end
    end

    current_nest = current_nest[k]
  end
end
extract_key_and_value(line) click to toggle source
# File lib/java-properties/parsing/parser.rb, line 39
def self.extract_key_and_value(line)
  # A line must be handled char by char to handled escaped '=' chars in the key name
  key          = StringIO.new
  value        = StringIO.new
  key_complete = false
  last_token   = ''
  line.each_char do |char|
    if !key_complete && char == KEY_VALUE_MARKER && last_token != KEY_ESCAPE
      key_complete = true
    else
      (key_complete ? value : key) << char
    end
    last_token = char
  end
  [key.string, value.string]
end