philiprehberger-ini_parser
INI file parser and writer with section support and type coercion
Requirements
- Ruby >= 3.1
Installation
Add to your Gemfile:
gem "philiprehberger-ini_parser"Or install directly:
gem install philiprehberger-ini_parserUsage
require "philiprehberger/ini_parser"
config = Philiprehberger::IniParser.parse(<<~INI)
name = MyApp
[database]
host = localhost
port = 5432
ssl = true
INI
config["name"] # => "MyApp"
config["database"]["port"] # => 5432
config["database"]["ssl"] # => trueLoading from a File
config = Philiprehberger::IniParser.load("config.ini")Serializing to INI
hash = {
"name" => "MyApp",
"database" => { "host" => "localhost", "port" => 5432 }
}
ini_string = Philiprehberger::IniParser.dump(hash)
Philiprehberger::IniParser.save(hash, "output.ini")Inline Comments
config = Philiprehberger::IniParser.parse(<<~INI)
host = localhost ; the server host
port = 8080 # default port
INI
config["host"] # => "localhost"
config["port"] # => 8080Multiline Values
config = Philiprehberger::IniParser.parse("description = this is a\\\n long value", coerce_types: false)
config["description"] # => "this is a long value"Escape Sequences
config = Philiprehberger::IniParser.parse('msg = hello\nworld', coerce_types: false)
config["msg"] # => "hello\nworld"Disabling Type Coercion
config = Philiprehberger::IniParser.parse(ini_string, coerce_types: false)
config["database"]["port"] # => "5432" (remains a string)Merging Configurations
base = Philiprehberger::IniParser.load("defaults.ini")
local = Philiprehberger::IniParser.load("local.ini")
merged = Philiprehberger::IniParser.merge(base, local)Comparing Configurations
a = Philiprehberger::IniParser.load("old.ini")
b = Philiprehberger::IniParser.load("new.ini")
diff = Philiprehberger::IniParser.diff(a, b)
diff[:added] # => {"section" => {"new_key" => "value"}}
diff[:removed] # => {"section" => {"old_key" => "value"}}
diff[:changed] # => {"section" => {"key" => {from: "old", to: "new"}}}Listing Sections
sections = Philiprehberger::IniParser.sections("config.ini")
# => ["database", "logging", "cache"]API
| Method | Description |
|---|---|
IniParser.parse(string, coerce_types: true) |
Parse an INI string into a Hash |
IniParser.load(path, coerce_types: true) |
Parse an INI file into a Hash |
IniParser.dump(hash) |
Serialize a Hash to an INI string |
IniParser.save(hash, path) |
Write a Hash to an INI file |
IniParser.merge(base, override) |
Deep merge two INI configurations |
IniParser.diff(a, b) |
Compare two parsed hashes and return added, removed, and changed keys |
IniParser.sections(string_or_path) |
Extract section names without fully parsing values |
Development
bundle install
bundle exec rspec
bundle exec rubocopSupport
If you find this project useful: