class Map_arg

A KISS cli argument parser.

Simply require and call Map_arg.new and then use it's argv method. You can quickly specify arguments that need value (a.k.a. –arg=value) and aliases.

Example usage:

# file.rb
require 'map_arg'
args = Map_arg.new
args.mapped = ['input', 'output']
args.aliases = {
  'input' => ['i', 'file', 'f'],
  'output' => ['o']
}
puts args.argv[:name]
puts args.argv[:rest]
puts args.argv['input']
puts args.argv['output']
puts args.argv['help']
puts args.argv['version']

$ ruby file.rb --file a -o b --help thing
file.rb
thing
a
b
true
false
$

Attributes

aliases[RW]

Define aliases for an argument using a hash table of arrays containing the aliases For example:

require 'map_arg'
args = Map_arg.new
args.aliases = {'open' => ['o', 'append', 'a']}
puts args.argv['open']

How to use:

$ name -o
true
$ name -append
true
$
mapped[RW]

Define which arguments require a mapped value with an array For example:

require 'map_arg'
args = Map_arg.new
args.mapped << 'file'
puts args.argv['file']

How to use:

$ name --file thing
thing
$

Public Class Methods

new() click to toggle source

Create a new instance of Map_arg class

# File lib/map_arg.rb, line 66
def initialize
        @mapped = []
        @aliases = []
        @cache = nil
end

Public Instance Methods

argv() click to toggle source

Returns cli arguments mapped to a hash Here's what different keys of the return value contain

  • :name

A nice alias for $0

  • :rest

Remains of cli arguments. For example: `$ name hello world # [:rest] = ['hello', 'world']

  • value

A value of a mapped argument OR true if an argument isn't mapped

Hash's default value is false

Note that results are cached so you don't need to reassign them.

# File lib/map_arg.rb, line 90
def argv
        return @cache unless @cache == nil

        argv = {:rest => [], :name => $0}
        argv.default = false
        currnet_key = nil
        current_value = true
        
        i = 0
        while i < ARGV.size do
                if ARGV[i][0] == '-'
                        arg = unalias ARGV[i].gsub(/^--?/, '')
                        if @mapped.include? arg
                                if ARGV[i+1][0] == '-'
                                        argv[arg] = nil
                                else
                                        argv[arg] = ARGV[i+1]
                                        i += 1
                                end
                        else
                                argv[arg] = true
                        end
                else
                        argv[:rest] << ARGV[i]
                end
                i += 1
        end

        @cache = argv
        return argv
end

Private Instance Methods

unalias(str) click to toggle source
# File lib/map_arg.rb, line 123
def unalias(str)
        @aliases.each_pair do |key, value|
                return key if value.include? str
        end
        return str
end