Skip to content

Instantly share code, notes, and snippets.

@alesya-h
Created December 12, 2012 08:43
Show Gist options
  • Save alesya-h/4266161 to your computer and use it in GitHub Desktop.
Save alesya-h/4266161 to your computer and use it in GitHub Desktop.
class ConfigParseError < StandardError
def initialize(file_name,line,text)
@file_name,@line,@text = file_name,line,text
super("Error in config file #{@file_name} at line #{line}. Line content \"#{@text}\" is incorrect.")
end
end
class ConfigReader
LINE_CONTINUE = /\\\s*$/
def self.read_config(file_name)
result = {}
prepend = ""
section = "default"
result[section] = {}
File.open(file_name, "r") do |io|
line_number = 0
(io.readlines + [""]).each do |line|
line_number += 1
line.chomp!
unless prepend.empty?
line = prepend + line.strip
end
prepend = ""
case line
when LINE_CONTINUE
prepend = line.sub(LINE_CONTINUE,"")
next
when ""
next
end
if it=try_as_section_name(line)
section = it
result[section] ||= {}
next
end
match_data = line.match(/([^=]+)=\s*(.*)/)
if match_data
key, value = match_data[1].strip, match_data[2].strip
result[section][key] = value
else
throw ConfigParseError.new(file_name,line_number,line)
end
end
end
result
end
private
def self.try_as_section_name(line)
match = line.match(/^\s*\[\s*([^\[\]]+)\s*\]\s*$/)
match && match[1]
end
end
p ConfigReader.read_config(ARGV[0] || "test.ini")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment