Jul 21, 2017 Tags: devblog, programming, ruby
This is just a quick writeup of a new Ruby library that I published yesterday:
ruby-inih
.
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.
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:
1
2
3
4
5
"" # => nil (NilClass)
"true" # => true (TrueClass)
"false" # => false (FalseClass)
"100" # => 100 (Integer)
"3.14" # => 3.14 (Float)
As a result, INI data like this:
1
2
3
4
[server-1]
website = example.com
load = 0.900
last_user =
is parsed into this:
1
2
3
4
5
6
7
{
"server-1" => {
"website" => "example.com",
"load" => "0.900",
"last_user" => "",
},
}
and is returned to the user as this:
1
2
3
4
5
6
7
{
"server-1" => {
"website" => "example.com",
"load" => 0.9,
"last_user" => nil,
},
}
ruby-inih
can be installed via gem
:
1
$ 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:
1
2
3
4
5
6
7
8
9
10
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.
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