Class: ParseOpt

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

Instance Method Summary collapse

Constructor Details

#initialize(usage = nil) {|self| ... } ⇒ ParseOpt

Creates a new instance.

Yields itself if called with a block.

Parameters:

  • usage (String) (defaults to: nil)

    usage banner.

Yield Parameters:

  • self (ParseOpt)

    Option parser object



25
26
27
28
29
# File 'lib/parseopt.rb', line 25

def initialize(usage = nil)
  @list = {}
  @usage = usage
  yield self if block_given?
end

Instance Method Details

#on(short, long = nil, help = nil) {|value| ... } ⇒ Object

Creates an option.

The block is called with the value when the option is found.

Examples:

Simple boolean

opts.on('b') { $bool = true }

Simple string with value

opts.on('s', 'string') { |value| $string = value }

Yield Parameters:

  • value

    value parsed



41
42
43
44
45
# File 'lib/parseopt.rb', line 41

def on(short, long = nil, help = nil, &block)
  opt = Option.new(short, long, help, &block)
  @list[short] = opt if short
  @list[long] = opt if long
end

#parse(args = ARGV) ⇒ Object

Parses all the command line arguments



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/parseopt.rb', line 48

def parse(args = ARGV)
  if args.member?('-h') or args.member?('--help')
    usage
    exit 0
  end
  seen_dash = false
  args.delete_if do |cur|
    opt = val = nil
    next false if cur[0] != '-' or seen_dash
    case cur
    when '--'
      seen_dash = true
      next true
    when /^--no-(.+)$/
      opt = @list[$1]
      val = false
    when /^-([^-])(.+)?$/, /^--(.+?)(?:=(.+))?$/
      opt = @list[$1]
      val = $2 || true
    end
    opt&.call(val)
  end
end

#usageObject

Generates the usage output (similar to ‘–help`)



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/parseopt.rb', line 78

def usage
  puts 'usage: %s' % @usage
  @list.values.uniq.each do |opt|
    s = '    '
    s << ''
    s << [opt.short&.prepend('-'), opt.long&.prepend('--')].compact.join(', ')
    s << ''
    s << '%*s%s' % [26 - s.size, '', opt.help] if opt.help
    puts s
  end
end

#usage=(value) ⇒ Object

Sets the usage banner



73
74
75
# File 'lib/parseopt.rb', line 73

def usage=(value)
  @usage = value
end