Class: Excavator::ParamParser

Inherits:
Object
  • Object
show all
Defined in:
lib/excavator/param_parser.rb

Overview

Public: ParamParser is a strategy object to integrate Command, Param, and OptionParser to parse commandline arguments.

ParamParser is the heart of Excavator. It takes Params and a Command and creates a command line parser that:

  • automatically assigns short and long switches for params (e.g. :name => –name or -n)

  • parsers arguments into named parameters

  • assigns default values to parameters if specified

  • creates a help message

  • verifies required params are passed - throws an error if they are not

Examples

parser = Excavator::ParamParser.new
parser.build(
  :name => "command_name",
  :desc => "command description",
  :params => [ <Param>, <Param>, ... ]
)

parser.parse!(ARGV)
# => { :param1 => "val", :param2 => "val2", ... }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeParamParser

Returns a new instance of ParamParser.



35
36
37
38
39
# File 'lib/excavator/param_parser.rb', line 35

def initialize
  @parser = OptionParser.new
  @parsed_params = {}
  @params = []
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



33
34
35
# File 'lib/excavator/param_parser.rb', line 33

def name
  @name
end

Instance Method Details

#build(options = {}) ⇒ Object

Public: Builds the parser up with the name, description and Params passed in.

This builds an OptionParser object with a “-h” and “–help” option.

options - A Hash of parameters needed to build the parser.

:name - A String/Symbol name of the Command.
:desc - A String description of the command.
:params - An Array of Params.

Examples

ParamParser.new.build({
  :name => "test_command",
  :desc => "description",
  :params => [<Param>, <Param>]
})

Returns nothing.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/excavator/param_parser.rb', line 60

def build(options = {})
  @name   = options[:name] #if options[:name]
  @params = options[:params] #if options[:params]
  @desc   = options[:desc] #if options[:desc]

  required_params = []
  optional_params = []

  @parser.banner = @desc
  @parser.separator ""
  @parser.separator "USAGE: #{@name} [options]"
  @params.each do |param|
    opts = []

    # Long option
    opts << "--#{param.name.to_s.gsub("_", "-")}"

    # params require an argument (for now)
    opts << "=#{param.name.to_s.upcase}"

    # Short option
    opts << short_switch(param)

    opts << param.desc if param.desc
    opts << "Defaults to: #{param.default}" if param.default

    opts << Proc.new do |val|
      @parsed_params[param.name] = val
    end

    opts.compact!

    if param.required?
      required_params << opts
    else
      optional_params << opts
    end
  end

  if required_params.size > 0
    @parser.separator ""
    @parser.separator "REQUIRED:"
    required_params.each { |opts| @parser.on(*opts) }
  end

  if optional_params.size > 0
    @parser.separator ""
    @parser.separator "OPTIONAL:"
    optional_params.each { |opts| @parser.on(*opts) }
  end

  @parser.separator ""
  @parser.on_tail("-h", "--help", "This message.") do
    puts usage
    exit 1
  end
end

#parse!(args) ⇒ Object

Public: Parses command line arguments. Any argument matching Params are removed from the argument list (destructive!) and returned in a hash.

args - An Array of command line arguments. This is usually ARGV.

If the last argument in the Array is a Hash, it is used as the
default parameters. This is a convience method to pass arguments
in a Hash form rather than an Array like ARGV.

Examples

parser = ParamParser.new
parser.build({...})

# Standard usage - assuming there is :name param.
args = ["command", "--name", "hello"]
parser.parse!(args)
# => {:name => "hello"},
# => args is now ["command"]

# Same as above, but the hash is checked to see whether or not
# the required params are met.
parser.parse!([{:name => "hello"}])
# => {:name => "hello"}

# Assume :name is required
parser.parse!(["command"])
# => Raises MissingParamsError

Returns a Hash of Symbol names to values. Raises Excavator::MissingParamsError if args is missing required params.



148
149
150
151
152
153
154
155
156
# File 'lib/excavator/param_parser.rb', line 148

def parse!(args)
  @parsed_params = args.last.is_a?(Hash) ? args.pop : {}

  @parser.parse!(args)
  set_default_params
  detect_missing_params!

  @parsed_params
end

#usageObject

Public: Print out a help message for this parser.



159
160
161
# File 'lib/excavator/param_parser.rb', line 159

def usage
  @parser.to_s
end