E_NO_SUCH_BLOG

Programming, philosophy, pedaling.


Introducing ruby-inih

Jul 21, 2017

Tags: ruby, programming, devblog

This is just a quick writeup of a new Ruby library that I published yesterday: ruby-inih.

Background

As far as I can tell, there are only two big INI libraries for Ruby: inifile and iniparse.

The former hasn’t been updated in nearly three years (and has open issues for parsing errors), while the latter is regularly updated but has some non-standard features (in particular, key duplication and “anonymous” pairs).

Both also wrap the parsed INI data into objects that act like Hash instances, but aren’t really. Introducing these intermediate objects produces unnecessary complexity, which is exactly why the standard JSON and YAML modules prefer to define their respective serialization and parsing functions between String and Hash objects.

I was unsatisfied with these choices, so I wrote ruby-inih as a new alternative.

Implementation

ruby-inih is really just a thin Ruby wrapper over inih, a simple INI parser written in C.

inih itself just calls a handler function for each line it parses, with ruby-inih providing a handler that collects the parsed results into an intermediate Hash. That Hash then gets “normalized,” meaning that values get coerced into their proper types:

"" # => nil (NilClass)
"true" # => true (TrueClass)
"false" # => false (FalseClass)
"100" # => 100 (Integer)
"3.14" # => 3.14 (Float)

As a result, INI data like this:

[server-1]
website = example.com
load = 0.900
last_user =

is parsed into this:

{
    "server-1" => {
        "website" => "example.com",
        "load" => "0.900",
        "last_user" => "",
    },
}

and is returned to the user as this:

{
    "server-1" => {
        "website" => "example.com",
        "load" => 0.9,
        "last_user" => nil,
    },
}

Installation and Usage

ruby-inih can be installed via gem:

$ gem install inih

It’s a native module, so make sure that you have your Ruby development headers and toolchain installed.

Once installed, using ruby-inih is incredibly simple — it only provides two public methods:

require "inih"

# parse from a string
INIH.parse <<~EOINI
  [section]
  key = value
EOINI

# read a file and parse its contents
INIH.load "my_conf.ini"

Both return a Hash instance as described above.

ruby-inih’s documentation is also available on RubyDocs, but the examples above cover the entire API.

Summary

Since ruby-inih does so little, I probably won’t update it very frequently, other than ensuring that it works with future stable Ruby releases.

If you’ve been looking for a library that converts INI files directly into Ruby hashes with as little fuss as possible, feel free to give it a try!

- William