How to Read an Ini File in Ruby

How to read an INI file in ruby

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

Editing ini files with ruby, clean way preferred

You say:

as I understand its functions I can't open a file, edit its contents and save back to disk.

You can do this fairly easily:

require 'inifile'

# Open and read the file
ini = IniFile.load('my_file.ini')

# Read its current contents
puts ini['section1']['foo']

# Edit the contents
ini['section1']['foo'] = 'baz'

# Save it back to disk
# You don't need to provide the filename, it remembers the original name
ini.save

Rails where to put configuration like ini files?

There isn't really anything built in to rails to do this, but luckily there's a great plugin called settingslogic which lets you externalise your settings.

Having said that I personally like to make these things constants in my model, so for example I'd have something like this:

class Person < AR:B
DEFAULT_PER_PAGE = 10
end

parse a ini like file with ruby

Here's what I came up with. First, the usage:

t = Testfile.new('ini.txt')
t.parse

t.sections.count
#=>2

t.sections.first
#=> #<Section:0x00000002d74b30 @parameters={"X"=>"10", "Y"=>"20"}, @cases={"C"=>"1", "A"=>"1234", "B"=>"12345"}>

As you can see, I made the Section contain both the parameters and the cases--just a judgement call, it could be done other ways. The implementation:

class Testfile
attr_accessor :filename, :sections

def initialize(filename)
@sections = []
@filename = filename
end

def parse
@in_section = false
File.open(filename).each_line do |line|
next if line =~ /^#?\s*$/ #skip comments and blank lines
if line.start_with? "["
if not @in_section
@section = Section.new
@sections << @section
end
@in_section = true
key, value = line.match(/\[(.*?):(.*?)\]/).captures rescue nil
@section.parameters.store(key, value) unless key.nil?
else
@in_section = false
key, value = line.match(/(\w+) ?= ?(\d+)/).captures rescue nil
@section.cases.store(key, value) unless key.nil?
end
end
@sections << @section
end
end

class Section
attr_accessor :parameters, :cases

def initialize
@parameters = {}
@cases = {}
end
end

Most of this code is the parsing. It looks for a line beginning with [ and creates a new Section object (unless it is already parsing a section). Any other non-comment line is parsed as a test case.

Ruby: Section an ansible hosts file into nested array

Direct INI Parse

If you don't want to do a full parse, you can treat your corpus as an INI file with sections. Such files can be tricky and have numerous edge cases, especially if you can't rigorously define how sections are separated. However, the following will work with your specific corpus.

# Read the file.
ini = File.read '/tmp/example.ini'

# Split the file into sections. Assumes only one blank line between
# sections.
sections = ini.scan /^\[.*?(?:\n\n|\z)/m

# Return an array of hashes, then merge them. Use the first element
# from each split as the hash key.
hash = sections.map do |section|
array = section.split
key = array.shift.delete '[]'
{ key => array }
end.reduce({}, :merge)

#=> {"group1"=>["host1", "host2"], "group2"=>["host3", "host4"]}

There are all kinds of ways this can fail on a more complex INI-like file, so you may need to do a more comprehensive parse of your file if you go this route. Alternatively, you can just save the result as a file, and then parse the inventory into a Ruby hash using the Ansible CLI.

Read text file from web and assign to variable in Ruby / Chef

Within Chef, the correct approach is to use the Chef::HTTP client.

Chef::HTTP.new('https://example.com/').get('/string.txt')

Ruby String read from file outputting backslashes

I the data read from the file the backslashes are part of the data.
in your string2 the backslashes are escape characters.

There are pr1obably better ways to to this but , you could probably just use gsub to get ride of the backslashes. try this and see if it does what you want

string1.gsub(/[\\\"]/,"")

if you just want to remove the /'s

string1.gsub(/\\/,"") should work also


Related Topics



Leave a reply



Submit