Skip to content

Instantly share code, notes, and snippets.

@gmcmillan
Created April 4, 2012 17:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmcmillan/2304284 to your computer and use it in GitHub Desktop.
Save gmcmillan/2304284 to your computer and use it in GitHub Desktop.
my.cnf parser
def self.parse_config(file)
config = {}
File.open(file).each_line do |line|
line.strip!
# skip lines with comments or blank lines
next if /^\#/.match(line)
next if /^\s*$/.match(line)
# store which group in the config the line belongs to (e.g. [mysqld])
if(/^\[(.+?)\]/.match(line))
@group = $1
end
# match "'key' and 'key val'
if(/^([\w\d\_\-]+)\s*([\w\d\_\-]+)$/.match(line))
param, value = line.split(/\s+/, 2)
# match 'key = val' or 'key=val' etc.
elsif(/^(.+?)\s*[=]\s*(.+)$/.match(line))
param, value = line.split(/\s*=\s*/, 2)
end
var_name = "#{param}".chomp.strip
if value.nil?
# variables without a declared value should be set to true
new_value = true
else
value = value.chomp.strip
if value =~ /^['"](.*)['"]$/
new_value = $1
else
new_value = value
end
end
if @group.nil?
config["#{var_name}"] = new_value
else
config["#{@group}"] = {} if config["#{@group}"].nil?
config["#{@group}"]["#{var_name}"] = new_value unless var_name.empty?
end
end
return config
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment