Class: ConfParser

Inherits:
Hash
  • Object
show all
Includes:
Template
Defined in:
lib/confparser.rb

Defined Under Namespace

Modules: Template Classes: Section

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Template

included

Constructor Details

#initialize(io) ⇒ ConfParser

Returns a new instance of ConfParser.



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/confparser.rb', line 88

def initialize (io)
  @parent, section, key, lineno = {}, nil, nil, 0

  io.each_line {|line|
    lineno += 1

    case line
    when /^\s*[;#]/ then next
    when /^\s*(.+?)\s*[=:]\s*(.*)$/
      if section
        __set__(section, Section.new(self)) unless self[section]
        key, self[section][key] = $1, $2
      else
        key, self[key] = $1, $2
      end
    when /^\s*\[(.+?)\]\s*$/
      section, key = $1, nil
    else
      if key
        if section
          __set__(section, Section.new(self)) unless self[section]
          self[section][key] = '' unless self[section][key]
          self[section][key] += "\n" + line
        else
          __set__(key, '') unless self[key]
          self[key] += "\n" + line
        end
      else
        raise "Syntax error at line #{lineno}" unless line =~ /^\s*$/
      end
    end
  }
  io.close
end

Class Method Details

.from_file(file) ⇒ Object



70
71
72
73
# File 'lib/confparser.rb', line 70

def from_file (file)
  return nil unless File.file?(file)
  self.new(File.open(file))
end

.from_io(io) ⇒ Object



75
76
77
78
# File 'lib/confparser.rb', line 75

def from_io (io)
  return nil unless io.is_a?(IO)
  self.new(io)
end

.from_string(str) ⇒ Object



80
81
82
83
# File 'lib/confparser.rb', line 80

def from_string (str)
  return nil unless str.is_a?(String)
  self.new(StringIO.new(str))
end

Instance Method Details

#[]=(key, value) ⇒ Object

Raises:

  • (ArgumentError)


123
124
125
126
# File 'lib/confparser.rb', line 123

def []= (key, value)
  raise ArgumentError unless key.is_a?(String) and (value.is_a?(String) or value.is_a?(Hash))
  __set__(key.to_s, (value.is_a?(String) ? value.to_s : Section.from_hash(self, value)))
end

#save(path) ⇒ Object



128
129
130
131
132
# File 'lib/confparser.rb', line 128

def save (path)
  File.open(path, 'w') {|f|
    f.write(self.to_s)
  }
end