Class: Upoj::Opts

Inherits:
OptionParser
  • Object
show all
Defined in:
lib/upoj-rb/opts.rb

Overview

Customized version of ruby’s OptionParser.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Opts

Returns a new instance of Opts.



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/upoj-rb/opts.rb', line 37

def initialize *args
  options = args.extract_options!

  @funnel = options[:funnel] || HashWithIndifferentAccess.new
  @footer = options[:footer]
  @examples = options[:examples]

  width = options[:width] || 32
  indent = options[:indent] || (' ' * 2)
  super nil, width, indent

  @banner = options[:banner].kind_of?(Hash) ? summary_banner_section(options[:banner]) : options[:banner]
end

Instance Attribute Details

#funnelObject

Hash that will be filled with the values of all options that were defined without a block.

Examples

opts = Upoj::Opts.new
opts.on('--option'){ # do whatever }
opts.on('-f', '--fubar')
opts.on('--value VALUE')

ARGV          #=> [ '--option', '-f', '--value', 43 ]
opts.parse!

# retrieve options in funnel by default
opts.funnel   #=> { 'fubar' => true, 'value' => 43 }

# a funnel with initial values can be given at construction
funnel = { 'foo' => false }
opts = Upoj::Opts.new :funnel => funnel


27
28
29
# File 'lib/upoj-rb/opts.rb', line 27

def funnel
  @funnel
end

Class Method Details

.section_title(title) ⇒ Object



29
30
31
# File 'lib/upoj-rb/opts.rb', line 29

def self.section_title title
  Paint[title, :bold]
end

.section_title_ref(ref) ⇒ Object



33
34
35
# File 'lib/upoj-rb/opts.rb', line 33

def self.section_title_ref ref
  Paint[ref, :underline]
end

Instance Method Details

#help!Object



69
70
71
# File 'lib/upoj-rb/opts.rb', line 69

def help!
  self.on('-h', '--help', 'show this help and exit'){ puts self; exit 0 }
end

#on(*args) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# File 'lib/upoj-rb/opts.rb', line 51

def on *args
  if block_given?
    super(*args)
  else
    sw = make_switch(args)[0]
    name = sw.long.first.sub /^\-+/, ''
    block = lambda{ |val| @funnel[name] = val }
    super(*args, &block)
  end
end

#program_nameObject



61
62
63
# File 'lib/upoj-rb/opts.rb', line 61

def program_name
  @program_name || File.basename($0)
end

#to_sObject



65
66
67
# File 'lib/upoj-rb/opts.rb', line 65

def to_s
  "#{super}#{summary_examples_section}#{@footer}"
end

#usage!Object



73
74
75
# File 'lib/upoj-rb/opts.rb', line 73

def usage!
  self.on('-u', '--usage', 'show this help and exit'){ puts self; exit 0 }
end