Module: CLI::ModularOptions

Defined in:
lib/cli/modular_options.rb

Overview

Use ‘include CLI::ModularOptions’ in a class whose instances will consume procs declared using CLI::WithOptions#cli_options to configure instances of OptionParser.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.ancestral_hooks(mod) ⇒ Array<Proc>

Get parser configuration procs belonging to or inherited by the specified class or module.

Parameters:

  • mod (Class, Module)

Returns:

  • (Array<Proc>)


55
56
57
# File 'lib/cli/modular_options.rb', line 55

def self.ancestral_hooks( mod )
  hooks_from(*mod.ancestors.uniq.reverse)
end

.hooks_from(*modules) ⇒ Array<Proc>

Get parser configuration procs belonging to the specified modules. Inheritance is not considered.

Parameters:

  • modules

    list of classes and modules that may or may not have cli_options procs

Returns:

  • (Array<Proc>)

    all cli_options procs belonging to specified modules



45
46
47
48
49
# File 'lib/cli/modular_options.rb', line 45

def self.hooks_from( *modules )
  modules.map{ |m|
    m.instance_variable_get :@cli_options_hooks if m.instance_variable_defined? :@cli_options_hooks
  }.flatten.compact
end

Instance Method Details

#configure_cli_parser(parser, hooks) ⇒ Object

Configures a given parser by passing it to the given hook procs, which are called in the context of self

Parameters:

  • parser (OptionParser)

    the parser to be configured

  • hooks (Array<Proc>)

    parser configuration procs declared with cli_options



35
36
37
38
39
# File 'lib/cli/modular_options.rb', line 35

def configure_cli_parser( parser, hooks )
  hooks.each do |b|
    instance_exec parser, &b
  end
end

#new_cli_parser(mod = self.class) ⇒ OptionParser

Constructs a new instance of OptionParser and configures it using the cli_options blocks declared in modules found in the inheritance chain of a class or module. If a class or module is not specified, the class of self is assumed.

Parameters:

  • mod (Class, Module) (defaults to: self.class)

    Optional, take cli_options from a different class

Returns:

  • (OptionParser)

    configured parser instance



24
25
26
27
28
# File 'lib/cli/modular_options.rb', line 24

def new_cli_parser( mod = self.class )
  OptionParser.new do |p|
    configure_cli_parser p, CLI::ModularOptions.ancestral_hooks(mod)
  end
end