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

ConfigParser can be used much like OptionParser, where the parser can set values into a config hash.

parser = ConfigParser.new
parser.on '-s', '--long LONG', 'a standard option' do |value|
  parser[:long] = 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 --long arg --switch --flag c')
# => ['a', 'b', 'c']

parser.config     
# => {:long => 'arg', :switch => true, :flag => true}

parser.to_s
# => %q{
#     -s, --long LONG             a standard option
#     --[no-]switch               a switch
#     --flag                      a flag
# }

ConfigParser formalizes this pattern of setting values into a config hash as they occur, and adds the ability to specify default values.

parser = ConfigParser.new
parser.add :flag, false            # false as a default makes a --flag
parser.add :switch, true           # true makes a --[no-]switch
parser.add :list, []               # an array makes a list-style option
parser.add :opt, 'default'         # all others make an ordinary option

parser.parse('a b c')              # => ['a', 'b', 'c']
parser.config
# => {
#   :flag   => false,
#   :switch => true,
#   :list   => [],
#   :opt    => 'default'
# }

args = %w{a b --flag --no-switch --list one --list two,three --opt value c}
parser.parse(args)                 # => ['a', 'b', 'c']
parser.config
# => {
#   :flag   => true,
#   :switch => false,
#   :list   => ['one', 'two', 'three'],
#   :opt    => 'value'
# }

Options can be defined using arguments just like on, or with an attributes hash. A block can be given to process values before they are set as configs.

parser = ConfigParser.new
parser.add(:x, nil, '--one', 'by args') {|value| value.upcase }
parser.add(:y, nil, :long => 'two', :desc => 'by hash')

parser.parse('a b --one value --two value c')
# => ['a', 'b', 'c']

parser.config
# => {:x => 'VALUE', :y => 'value'}

Installation

ConfigParser is available as a gem via Gemcutter.

% gem install config_parser

Info

Copyright © 2010, Simon Chiang

License

MIT-Style