Class: ConfUtils::IniFile

Inherits:
Object
  • Object
show all
Defined in:
lib/props/ini.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ IniFile

Returns a new instance of IniFile.



20
21
22
# File 'lib/props/ini.rb', line 20

def initialize( text )
  @text = text
end

Class Method Details

.load(text) ⇒ Object



15
16
17
# File 'lib/props/ini.rb', line 15

def self.load( text )
  IniFile.new( text ).parse
end

.load_file(path) ⇒ Object

returns a nested hash

(compatible structure - works like YAML.load_file)


10
11
12
13
# File 'lib/props/ini.rb', line 10

def self.load_file( path )
  text = File.open( path, 'r:bom|utf-8' ).read
  self.load( text )
end

Instance Method Details

#parseObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/props/ini.rb', line 24

def parse
  hash = top_hash = Hash.new

  text = @text
  text = text.gsub( "\t", ' ' )   # replace all tabs w/ spaces

  text.each_line do |line|

    ### skip comments
    #  e.g.   # this is a comment line
    #  or     ; this too
    #  or     --  haskell style
    #  or     %   text style

    if line =~ /^\s*#/ || line =~ /^\s*;/ || line =~ /^\s*--/ || line =~ /^\s*%/
      ## logger.debug 'skipping comment line'
      next
    end

    ### skip blank lines
    if line =~ /^\s*$/ 
      ## logger.debug 'skipping blank line'
      next
    end

    # pass 1) remove possible trailing eol comment
    ##  e.g    -> New York   # Sample EOL Comment Here (with or without commas,,,,)
    ## becomes -> New York

    line = line.sub( /\s+#.*$/, '' )

    # pass 2) remove leading and trailing whitespace
    
    line = line.strip
 
    ## check for new section e.g.  [planet012-xxx_bc]

    ### todo: allow _ or - in strict section key? why? why not??
    ###   allow _ or - in value key? why why not??
    if line =~ /^\s*\[\s*([a-z0-9_\-]+)\s*\]\s*$/   # strict section
      key = $1.to_s.dup
      hash = top_hash[ key ] = Hash.new
    elsif line =~ /^\s*\[\s*([^ \]]+)\s*\]\s*$/     # liberal section; allow everything in key
      key = $1.to_s.dup
      hash = top_hash[ key ] = Hash.new
    elsif line =~ /^\s*([a-z0-9_\-]+)\s*[:=](.*)$/
      key   = $1.to_s.dup
      value = $2.to_s.strip.dup   # check if it can be nil? if yes use blank string e.g. ''
      ### todo:  strip quotes from value??? why? why not?
      hash[ key ] = value
    else
      puts "*** warn: skipping unknown line type in ini >#{line}<"
    end
  end # each lines

  top_hash
end