A Ruby ConfigParser

It’s high-time I got back to doing some Ruby, right?

I like Python’s ConfigParser and I decided to make my own for Ruby. Not because there isn’t any out there (I’m sure there is) but because I wanted to practice making a class, and a module, etc.

Well, it took me all of 30 minutes, most of which was trying to track down a stupid syntax error. The module is short and sweet. It doesn’t do anything fancy — it doesn’t have multiple configs like Python’s and it only understands comments starting at the beginning of the line. And it’s not very robust, but it seems to work.

You can grab it here and, using the sample file I also put there, here is the output:

irb(main):001:0> require "configparser"
=> true
irb(main):002:0> p=ConfigParser.new("sample.ini")
=> {"key1"=>"val1", "key2"=>"val2", "key3"=>"this is a value with spaces, and it may work!"}
irb(main):004:0> p.each_key {|k| puts("#{k}=#{p[k]}”)}
key1=val1
key2=val2
key3=this is a value with spaces, and it may work!

The code isn’t big, but the concepts are. In it, I used inheritence and outside modules. And it worked with no problem at all.

2 Responses to “A Ruby ConfigParser”

  1. JimBowen Says:

    Nice! But I can’t get it.. :( The stuff exists (tried sample.ini for instance) but the server won’t list the directory contents.

  2. Mike Says:

    Oops. I fixed the link. Thanks Jim.

Leave a Reply

You must be logged in to post a comment.