ConfigParser

Parse command-line options into a configuration hash.

Description

ConfigParser is an analogue of OptionParser that formalizes the pattern of setting parsed options into a hash. ConfigParser uses a similar, simplified declaration syntax and provides an API that integrates well with libraries like Configurable.

Usage

Define options and their default values using add:

parser = ConfigParser.new
parser.add :option, 'default'      # regular option with a default value
parser.add :switch, true           # true makes a --[no-]switch
parser.add :flag, false            # false as a default makes a --flag
parser.add :list, []               # an array makes a list-style option

parser.parse 'a b --flag --list x --list y,z c'
# => ['a', 'b', 'c']

parser.config
# => {
#   :option => 'default',
#   :switch => true,
#   :flag   => true,
#   :list   => ['x', 'y', 'z']
# }

The OptionParser on syntax may also be used, if desired (most syntax variations will work). Use the parser as if it were the config hash:

parser = ConfigParser.new
parser.on '--option OPTION', 'a standard option' do |value|
  parser[:option] = value
end

parser.on '--[no-]switch', 'a switch' do |value|
  parser[:switch] = value
end

parser.on '--flag', 'a flag' do
  parser[:flag] = true
end

parser.parse 'a b --flag --switch --option value c'
# => ['a', 'b', 'c']

parser.config
# => {
#   :option => 'value',
#   :switch => true,
#   :flag   => true
# }

Added options may be further defined using arguments just like on or with an attributes hash. Notably, the key for the config does not have to correspond to the option (although by default it does). As you may expect a block can be given to process values before they are set as configs.

parser = ConfigParser.new

# use args to define the option
parser.add(:x, nil, '-o', '--one')

# use an options hash to define the option
parser.add(:y, nil, :short => 't', :long => 'two')

# use a block to process the values
parser.add(:z, nil, :long => 'three') {|value| value.upcase }

parser.parse('a b --one uno --two dos --three tres c')
# => ['a', 'b', 'c']

parser.config
# => {:x => 'uno', :y => 'dos', :z => 'TRES'}

Installation

ConfigParser is available as a gem.

% gem install config_parser

Development

To get started, checkout the code from GitHub and run the tests:

git clone git://github.com/thinkerbot/config_parser.git
cd config_parser
rake test

Please report any issues here.

Info

Developer

Simon Chiang

License

MIT-Style