Posts Tagged ‘ gem ’

ColorTail Gem

Tuesday, April 20th, 2010

One of the best ways to learn something new is to find a project in that realm and do it. I wanted to learn Ruby on Rails, so I wrote a web site. I wanted to learn Python, so I did a project in it for work. Now I want to get better at Ruby, so I wrote a gem. It’s usually not as simple as just picking a project though. It’s much easier to pick and complete a project if you are filling a need. So that’s what I did, I filled a need.
(more…)

Parsing Ini Files With Ruby

Sunday, October 11th, 2009

There doesn’t seem a lot of documentation or examples about parsing ini files in Ruby. There are definitely shortcut ways to do it and I could always write my own methods, but why reinvent the wheel when there are gems? So start out by simply installing the inifile gem.

1
2
3
4
5
beacon:~ elubow$ sudo gem install inifile
Successfully installed inifile-0.1.0
1 gem installed
Installing ri documentation for inifile-0.1.0...
Installing RDoc documentation for inifile-0.1.0...

The code for the gem is available from github here. Other inifile documentation is available here. The rest of the inifile documentation is a good reference but doesn’t contain any examples.

For some reason (which I don’t understand so please feel free to explain it in the comments if you know), you have to do more than just the standard require statement for this gem. At the top of your Ruby code, add the lines below. Make sure that you replace the directory location with your directory location.

1
2
3
require 'rubygems'
$:.unshift( '/usr/lib64/ruby/gems/1.8/gems/inifile-0.1.0/lib/' )
require 'inifile'

A short example of the ini file that we will be working with:

1
2
3
4
[foo]
bar = "baz"
dir = "2009-10-05/"
id = 75

To get the id parameter of the ini file assuming you know its in the [foo]section, you can use the code below. Notice the parameter section of the new object instantiator. The reason for this is that ini files are pretty abstract can have a few variations on format. Therefore you can specify the comment style and parameter definition style during object instantiation. My ini files use the ‘=’ to assign parameters

1
2
3
  ini = IniFile.new( options[:conf], :parameter => '=' )
  section = ini[foo]
  id = section['id']

Using the above code the id variable now contains the contents of the id parameter from the ini file.