Class: SubCmdOptParser

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

Defined Under Namespace

Classes: OptionParserForSubCmd

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(banner = nil, width = 32, indent = ' '*4, opts = {}) {|sc| ... } ⇒ SubCmdOptParser

Returns a new instance of SubCmdOptParser.

Parameters:

  • banner (String, nil) (defaults to: nil)

    An argument of OptionParser

  • width (Fixnum) (defaults to: 32)

    An argument of OptionParser

  • indent (String) (defaults to: ' '*4)

    An argument of OptionParser

  • opts (Hash) (defaults to: {})

    Options hash

Options Hash (opts):

  • :help_command (boolean)

    If the value is false then subcommand help is not set automatically

Yields:

  • (sc)

Yield Parameters:



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/subcommand_optparse.rb', line 26

def initialize(*args, &block)
  opts = args.extract_options!
  @default_banner = args.shift
  @args_option_parser = args
  @global_option_setting = nil
  @subcommand = []
  @help_subcommand_use_p = (!opts.has_key?(:help_command) || opts[:help_command])
  if block_given?
    yield(self)
  end
end

Instance Method Details

#global_option {|opt| ... } ⇒ Object

Set options that are available for all subcommands

Yields:

  • (opt)

Yield Parameters:



41
42
43
# File 'lib/subcommand_optparse.rb', line 41

def global_option(&block)
  @global_option_setting = block
end

#parse!(argv = ARGV) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/subcommand_optparse.rb', line 95

def parse!(argv = ARGV)
  if @help_subcommand_use_p
    subcommand("help", :load_global_options => false)
  end

  subcmd = argv[0]
  if subcmd_data = get_subcmd_data(subcmd)
    argv.shift
  else
    subcmd = nil
  end
  opt = get_option_parser(subcmd, subcmd_data)
  opt.parse!(argv)

  if @help_subcommand_use_p && subcmd == "help"
    print opt.to_s + "\n"
    puts message_list_subcommands(opt)
    exit
  end

  subcmd
end

#subcommand(name, banner = nil, opts = {}) {|opt| ... } ⇒ Object

Parameters:

  • name (String)

    Name of subcommand

  • opts (Hash) (defaults to: {})

    Options hash

Options Hash (opts):

  • :load_global_options (boolean)

    If the value is false then global options are not loaded

Yields:

  • (opt)

Yield Parameters:



51
52
53
54
55
56
57
# File 'lib/subcommand_optparse.rb', line 51

def subcommand(name, *args, &block)
  opts = args.extract_options!
  banner = args.shift
  h = { :banner => banner, :setting => block }
  h[:load_global_options] = !(opts.has_key?(:load_global_options) && !opts[:load_global_options])
  @subcommand << [name, h]
end