Class: Benry::CLI::OptionParser

Inherits:
Object
  • Object
show all
Defined in:
lib/benry/cli.rb

Instance Method Summary collapse

Constructor Details

#initialize(option_schemas = []) ⇒ OptionParser

Returns a new instance of OptionParser.



126
127
128
129
130
131
132
133
134
135
136
# File 'lib/benry/cli.rb', line 126

def initialize(option_schemas=[])
  #; [!bflls] takes array of option schema.
  @option_schemas = option_schemas.collect {|x|
    case x
    when OptionSchema ; x
    when Array        ; OptionSchema.parse(*x)
    else
      raise OptionDefinitionError.new("#{x.inspect}: invalid option schema.")
    end
  }
end

Instance Method Details

#each_option_schema(&callback) ⇒ Object



156
157
158
159
# File 'lib/benry/cli.rb', line 156

def each_option_schema(&callback)
  #; [!ycgdm] yields each option schema.
  @option_schemas.each(&callback)
end

#each_option_stringObject



149
150
151
152
153
154
# File 'lib/benry/cli.rb', line 149

def each_option_string
  #; [!luro4] yields each option string and description.
  @option_schemas.each do |schema|
    yield schema.option_string, schema.desc
  end
end

#err(msg) ⇒ Object



161
162
163
# File 'lib/benry/cli.rb', line 161

def err(msg)
  OptionError.new(msg)
end

#option(symbol, defstr = nil, desc = nil, &callback) ⇒ Object



138
139
140
141
142
143
144
145
146
147
# File 'lib/benry/cli.rb', line 138

def option(symbol, defstr=nil, desc=nil, &callback)
  #; [!s59ly] accepts option definition string and description.
  #; [!2gfnh] recognizes first argument as option name if it is a symbol.
  unless symbol.is_a?(Symbol)
    symbol, defstr, desc = nil, symbol, defstr
  end
  @option_schemas << OptionSchema.parse(defstr, desc, name: symbol, &callback)
  #; [!fv5g4] return self in order to chain method call.
  self
end

#parse(args) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/benry/cli.rb', line 165

def parse(args)
  #; [!5jfhv] returns command-line options as hash object.
  #; [!06iq3] removes command-line options from args.
  #; [!j2fda] stops command-line parsing when '-' found in args.
  option_values = {}
  while args[0] && args[0].start_with?('-') && args[0] != '-'
    argstr = args.shift
    #; [!31h46] stops parsing when '--' appears in args.
    if argstr == '--'
      break
    #; [!w5dpy] can parse long options.
    elsif argstr.start_with?('--')
      parse_long_option(argstr, option_values)
    #; [!mov8e] can parse short options.
    else
      parse_short_option(args, argstr, option_values)
    end
  end
  return option_values
end