Class: XOptionParser

Inherits:
OptionParser
  • Object
show all
Defined in:
lib/xoptparse.rb,
lib/xoptparse/version.rb

Defined Under Namespace

Classes: Switch

Constant Summary collapse

VERSION =
'0.6.2'

Instance Method Summary collapse

Constructor Details

#initialize(description = nil, *args, &block) ⇒ XOptionParser

Returns a new instance of XOptionParser.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/xoptparse.rb', line 7

def initialize(description = nil, *args, &block)
  @commands = {}
  @banner_usage = 'Usage: '
  @banner_options = '[options]'
  @banner_command = '<command>'
  super(nil, *args) do |opt|
    if description
      opt.separator ''
      opt.separator description
    end
    block&.call(opt)
  end
end

Instance Method Details



33
34
35
36
37
38
39
40
41
42
# File 'lib/xoptparse.rb', line 33

def banner
  return @banner if @banner

  banner = +"#{@banner_usage}#{program_name}"
  banner << " #{@banner_options}" unless no_options
  visit(:add_banner, banner)
  banner << " #{@banner_command}" unless @commands.empty?

  banner
end

#command(name, desc = nil, *args, &block) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/xoptparse.rb', line 158

def command(name, desc = nil, *args, &block)
  name = name.to_s
  pattern = /^#{name.gsub('_', '[-_]?')}$/i
  sw0 = Switch::SummarizeArgument.new(pattern, nil, nil, nil, name, desc ? [desc] : [], nil) do
    self.class.new(desc, *args) do |opt|
      opt.program_name = "#{program_name} #{name}"
      block&.call(opt)
    end
  end
  top.append(sw0, nil, [sw0.arg])
  @commands[name] = sw0
  nil
end

#make_switch(opts, block = nil) ⇒ Object



71
72
73
74
75
76
77
78
# File 'lib/xoptparse.rb', line 71

def make_switch(opts, block = nil)
  sw = super(opts, block || proc {})
  sw0 = sw[0] = fix_arg_switch(sw[0])
  return sw if sw0.short || sw0.long

  long = sw0.arg_parameters.map(&:first)
  [sw0, nil, long]
end

#order!(*args, into: nil, **kwargs) ⇒ Object



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

def order!(*args, into: nil, **kwargs)
  return super(*args, into: into, **kwargs) if @commands.empty?

  @command_switch = nil
  argv = super(*args, into: into, **kwargs, &nil)
  return argv unless @command_switch

  into = into[@command_switch.arg.to_sym] = {} if into
  @command_switch.block.call.send(block_given? ? :permute! : :order!, *args, into: into, **kwargs)
end