Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dolzenko/327027 to your computer and use it in GitHub Desktop.
Save dolzenko/327027 to your computer and use it in GitHub Desktop.
parse_ini_file_using_enumerable_slice_before.rb
def parse_ini_file(file)
# Use +Enumerable#slice_before+ to slice ini file into sections where
# start of new section is detected with regexp matching the opening square bracket
file.each_line.slice_before(/\[/).each_with_object({}) do |section, config|
# Remove the first element which is the section header and extract header name
section_name = section.shift[/\[(?<section_name>.+?)\]/, :section_name] # use Oniguruma's named capture
# Use Hash[] class method to create parameters hash from key/value assoc array
section_parameters = Hash[section.map { |parameter| parameter.split("=").map(&:strip) }]
config[section_name] = section_parameters
end
end
if __FILE__ == $PROGRAM_NAME
require "pp"
puts "Parsing INI file:"
puts "================="
ini_file = <<-INI_FILE
[client]
port = 3306
socket = /tmp/mysql.sock
[mysqld]
port = 3306
socket = /tmp/mysql.sock
key_buffer = 384M
max_allowed_packet = 1M
table_cache = 512
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size = 32M
thread_concurrency = 8
log-bin=mysql-bin
server-id = 1
[mysqldump]
max_allowed_packet = 16M
[isamchk]
key_buffer = 256M
sort_buffer_size = 256M
read_buffer = 2M
write_buffer = 2M
[myisamchk]
key_buffer = 256M
sort_buffer_size = 256M
read_buffer = 2M
write_buffer = 2M
INI_FILE
pp parse_ini_file(ini_file)
# Prints:
#
# {"client"=>{"port"=>"3306", "socket"=>"/tmp/mysql.sock"},
# "mysqld"=>
# {"port"=>"3306",
# "socket"=>"/tmp/mysql.sock",
# "key_buffer"=>"384M",
# "max_allowed_packet"=>"1M",
# "table_cache"=>"512",
# "sort_buffer_size"=>"2M",
# "read_buffer_size"=>"2M",
# "read_rnd_buffer_size"=>"8M",
# "myisam_sort_buffer_size"=>"64M",
# "thread_cache_size"=>"8",
# "query_cache_size"=>"32M",
# "thread_concurrency"=>"8",
# "log-bin"=>"mysql-bin",
# "server-id"=>"1"},
# "mysqldump"=>{"max_allowed_packet"=>"16M"},
# "isamchk"=>
# {"key_buffer"=>"256M",
# "sort_buffer_size"=>"256M",
# "read_buffer"=>"2M",
# "write_buffer"=>"2M"},
# "myisamchk"=>
# {"key_buffer"=>"256M",
# "sort_buffer_size"=>"256M",
# "read_buffer"=>"2M",
# "write_buffer"=>"2M"}}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment