A very simple yet flexible configuration writer/reader library.
Add this line to your application's Gemfile:
gem 'nac'
And then execute:
$ bundle
Or install it yourself as:
$ gem install nac
The source config file and its path will be created if they don't already exist. The data is cached when the file is loaded and after a new value is saved.
This simple example shows how to load, write, and read.
require 'nac'
# load or create a new config
config = Nac::Config.new('my_config')
# set values
config.set('name', 'Chris')
config.set('color', 'Blue')
# get a single value
puts config.get('name')
# get all data
puts config.get
#=> { name: 'Chris', color: 'Blue' }
It's possible to read and write nested data by passing an array to the set
and get
methods.
require 'nac'
config = Nac::Config.new('my_config')
config.set(%[user name first], 'Homer')
config.set(%[user name last], 'Simpson')
puts config.get('user')
#=> { name: { first: 'Homer', last: 'Simpson' }}
puts config.get(%[user name])
#=> { first: 'Homer', last: 'Simpson' }
puts config.get(%[user name last])
#=> { last: 'Simpson' }
# nil is returned if the key doesn't exist
puts config.get(%[user name middle])
#=> nil
# Or you can specify the return value if the key doesn't exist
puts config.get(%[user name middle], 'J')
#=> 'J'
# Symbol arrays work too!
config.set(%i{look ma no}, 'hands')
puts config.get(:look)
#=> { ma: { no: 'hands' } }
template
: Optional value that will be converted to yaml and written to the config file. Default is{}
.init!
: When true, force the configuration file to be rewritten. Default isfalse
.
Note: One doesn't need to specify init!
when using template
.
The template will not be written if the configuration file exists.
However, using init!
will re-initialize the config file and the
template will be written. Similarly, template
is not required when
using init!
.
requre 'nac'
options = {
template: { some: { default: [:options] } },
init!: true
}
config = Nac::Config.new('my_config', options)
puts config.get
#=> { some: { default: [:options] } }
Bug reports and pull requests are welcome on GitHub at https://github.com/chris-roerig/nac.
The gem is available as open source under the terms of the MIT License.