Class: Rconftool::ConfigFile

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

Overview

Object to represent an entire configuration file. It consists of an array of Setting objects, with the first one having a special name (__header__). We also keep a hash of setting name => setting object to enable us to find a particular setting quickly.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename = nil) ⇒ ConfigFile

Returns a new instance of ConfigFile.



202
203
204
# File 'lib/rconftool.rb', line 202

def initialize(filename=nil)
  read(filename) if filename
end

Instance Attribute Details

#settingsObject (readonly)

Returns the value of attribute settings.



200
201
202
# File 'lib/rconftool.rb', line 200

def settings
  @settings
end

#versionObject (readonly)

Returns the value of attribute version.



200
201
202
# File 'lib/rconftool.rb', line 200

def version
  @version
end

Instance Method Details

#[](item) ⇒ Object

fetch a setting by name



207
208
209
# File 'lib/rconftool.rb', line 207

def [](item)
  @settings_hash[item]
end

#read(filename) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/rconftool.rb', line 211

def read(filename)
  @version = nil
  curr_setting = Setting.new(HEADER_ID,'')
  @settings = [curr_setting]
  @settings_hash = {}

  File.open(filename) do |f|
    # VERSION header must occur within first 20 lines
    20.times do
      line = f.gets
      break unless line
	  linetmp = line.chop + "\r\n"
      curr_setting << linetmp
      if line =~ /\A##VERSION:/
        @version = line.chop
        break
      end
    end
    raise NoVersionLine, "#{filename}: No VERSION line found" unless @version

    while line = f.gets
      unless line =~ /\A##NAME:(.*):(.*)/
linetmp = line.chop + "\r\n"
        curr_setting << linetmp
        next
      end
      curr_setting = Setting.new($1,$2)
      @settings << curr_setting
      @settings_hash[curr_setting.name] = curr_setting
    end
  end
end

#write(filename) ⇒ Object



244
245
246
247
248
249
250
251
# File 'lib/rconftool.rb', line 244

def write(filename)
  File.open(filename,"w") do |f|
    @settings.each do |s|
		stmp =  s.to_s.chop + "\r\n"
      f << stmp
    end
  end
end