Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an INI file in ruby

How do I read/write an ini file in ruby. I have an ini file that I need to

  1. read
  2. change an entry
  3. write out to a different location

How would I do that in ruby? The documentation on this is bleak.

like image 484
Andrew Redd Avatar asked Mar 03 '09 18:03

Andrew Redd


2 Answers

Use the InIFile Gem

As @method said, use the inifile gem. There is also an ini gem but I haven't used it.

I found the documentation here a slightly more helpful than the documentation here which is where the gem page links to.

There were not many examples so here is a bit of code to get you started:

Example Setup

First, create a file /tmp/desktop.ini with these contents:

[Desktop Entry]
Version=1.0
Type=Application
Name=Foo Viewer
Comment=The best viewer for Foo objects available!
TryExec=fooview
Exec=fooview %F
Icon=fooview

Make sure you have run gem install inifile from the command line.

Example Code

Create a file like /tmp/ini-test.rb with these contents:

require 'inifile'
require 'pp'

# read an existing file
file = IniFile.load('/tmp/desktop.ini')
data = file["Desktop Entry"]

#output one property
puts "here is one property:"
puts data["Name"]

# pretty print object
puts "here is the loaded file:"
pp file

# create a new ini file object
new_file = IniFile.new

# set properties
new_file["Desktop Entry"] = {
    "Type" => "Application",
    "Name" => 'test',
    "Exec" => 'command',
}

# pretty print object
puts "here is a object created with new:"
pp new_file

# set file path
new_file.filename = "/tmp/new_ini_file.ini"

# save file
new_file.write()
puts "the new object has been saved as a file to /tmp/new_ini_file.ini"

Example Results

Running that file with ruby /tmp/ini-test.rb should yield something like:

here is one property:
Foo Viewer

here is the loaded file:
{ this output hidden for brevity }

here is a object created with new:
#<IniFile:0x007feeec000770
 @comment=";#",
 @content=nil,
 @default="global",
 @encoding=nil,
 @escape=true,
 @filename=nil,
 @ini=
  {"Desktop Entry"=>
    {"Type"=>"Application",
     "Name"=>"test",
     "Exec"=>"command",
     "Icon"=>"icon_filename",
     "Comment"=>"comment"}},
 @param="=">

the new object has been saved as a file to /tmp/new_ini_file.ini

Modify as required suit your needs.

like image 187
cwd Avatar answered Nov 02 '22 10:11

cwd


I recently used ruby-inifile. Maybe it's overkill compared to the simple snippets here...

like image 12
method Avatar answered Nov 02 '22 09:11

method