Module: JavaProperties::Parser

Defined in:
lib/java_properties/parser.rb

Overview

Module for parsing Java properties text into a Hash.

props_hash = JavaProperties::Parser.parse( string_of_propfile_contents )

Class Method Summary collapse

Class Method Details

.normalize(text) ⇒ Object

Normalizes the contents of a Java properties file so that comments are removed, leading spaces are trimmed off, multiline entries are consolidated and all delimiters are consistent.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/java_properties/parser.rb', line 36

def self.normalize text
  # Remove comment lines
  text.gsub!( /^\s*[!\#].*$/, '' )
  # Remove all leading spaces
  text.gsub!( /^\s+/, '' )
  # Remove all trailing spaces
  text.gsub!( /\s+$/, '' )
  # Concatenate strings ending with \
  text.gsub!( /\\\s*$[\n\r]+/, '' )
  # Remove spaces next to delimiters and replace all with =
  text.gsub!( /^((?:(?:\\[=: \t])|[^=: \t])+)[ \t]*[=: \t][ \t]*/, '\1=' )
  
  text
end

.parse(text) ⇒ Object

Parses a string containing the contents of a Java properties file into a hash of key/value pairs. The keys are converted into symbols.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/java_properties/parser.rb', line 15

def self.parse text
  props = {}
  text = self.normalize(text)
  text.split(/[\n\r]+/).each do |line|
	if line =~ /^([^=]*)=(.*)$/ then
	  key,value = $1,$2
	elsif line =~ /\S/ then
	  key,value = line, ''
	else
	  key,value = nil,nil
	end
	props[Encoding.decode(key).to_sym] = Encoding.decode(value) unless key.nil? && value.nil?
  end
  props
end