Sha256: 2c67ebbcd62901731ba35e92456f95b534ebdba60378825983ee1a0ffbec4c50

Contents?: true

Size: 1.95 KB

Versions: 8

Compression:

Stored size: 1.95 KB

Contents

#!ruby
require 'ftools'
require 'tempfile'

class ConfigFile

  def ConfigFile::parse(filename)
	 # Make sure this file exists and is readable
	 if( FileTest::readable_real?(filename) )
		new(filename) # Return the class instance
	 else
		-1 # Return -1 on failure
	 end
  end

  def initialize(filename)
	 @filename	= filename
	 @config		= Hash::new() # The class internal variable that holds the config data
	 section		= ''

	 # Parse the configuration file (and in only TWO rows, God I love Ruby! =)
	 IO::foreach(@filename) { |configLine| @config[section = $1] = Hash::new() if(configLine.gsub(/\s*#.*$/, '') =~ /\s*(\S+)\s*\{/) 
	 @config[section].update({$1 => $2}) if(configLine.gsub(/\s*#.*$/, '') =~ /\s*(\S+)\s*=\s*(.*)/) }
  end

  # Return the requested parameter
  def getParam(section, parameter)
	 @config[section][parameter] if(@config[section].type == Hash)
  end

  # Set the provided parameter
  def setParam(section, parameter, value)
	 # Create a temp file
	 temp = Tempfile::new('config')

	 current_section = ''
	 # Loop through the config file
	 IO::foreach(@filename) { |line|
		current_section = $1 if( line =~ /^\s*(\S+)\s*{\s*(#.*)?$/ ) # Handle the section stuff
		# Is this a correct parameter entry?
		if( line =~ /^\s*(\S+)\s*=\s*\S+\s*(#.*)?$/ )
		  
		  if( current_section == section && $1 == parameter ) # This is the line we want to change!
			 line.gsub!( /^(\s*\S+\s*=\s*)\S+(\s*(#.*)?)$/, "\\1#{value}\\2" ) # Change the parameter value to the one the user supplied
		  end
		  
		end

		temp.puts(line) # Write the line to the tempfile
	 }

	 temp.close() # Close the file
	 File::copy(temp.path, @filename) # Copy the tempfile to overwrite the old one
	 temp.close(true) # Remove the file
  end

  # Loop through all sections
  def each_section()
	 @config.each { |key,value| yield(key) }
  end

  # Loop through all parameters in a section
  def each_parameter(section)
	 @config[section].each { |key,value| yield(key) }
  end

  attr_reader :filename

end

Version data entries

8 entries across 8 versions & 4 rubygems

Version Path
rwdaddresses-0.99 extras/config_file
rwdaddresses-0.98 extras/config_file
rwdaddresses-1.01 extras/config_file
rwddemo-0.91 extras/config_file
rwdschedule-0.98 extras/config_file
rwdschedule-0.97 extras/config_file
rwdshell-0.96 extras/config_file
rwdshell-0.97 extras/config_file