DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Evgeniy has posted 3 posts at DZone. View Full User Profile

Parse INI File Using Enumerable#slice_before

03.10.2010
| 1069 views |
  • submit to reddit
        More info in my blog post <a href="http://dolzhenko.org/blog/?p=85">Exploring Latest ruby-lib Additions</a>

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 flat key/value array
    section_parameters = Hash[*section.map { |parameter| parameter.split("=").map(&:strip) }.flatten]
    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