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.



198
199
200
# File 'lib/rconftool.rb', line 198

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

Instance Attribute Details

#settingsObject (readonly)

Returns the value of attribute settings.



196
197
198
# File 'lib/rconftool.rb', line 196

def settings
  @settings
end

#versionObject (readonly)

Returns the value of attribute version.



196
197
198
# File 'lib/rconftool.rb', line 196

def version
  @version
end

Instance Method Details

#[](item) ⇒ Object

fetch a setting by name



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

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

#read(filename) ⇒ Object



207
208
209
210
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
# File 'lib/rconftool.rb', line 207

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
      curr_setting << line
      if line =~ /\A##VERSION:/
        @version = line
        break
      end
    end
    raise NoVersionLine, "#{filename}: No VERSION line found" unless @version

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

#write(filename) ⇒ Object



238
239
240
241
242
243
244
# File 'lib/rconftool.rb', line 238

def write(filename)
  File.open(filename,"w") do |f|
    @settings.each do |s|
      f << s.to_s
    end
  end
end