Module: Shebang

Defined in:
lib/shebang.rb,
lib/shebang/option.rb,
lib/shebang/version.rb,
lib/shebang/command.rb

Overview

Shebang is a nice wrapper around OptionParser that makes it easier to write commandline executables.

Author:

Since:

Defined Under Namespace

Classes: Command, Error, Option

Constant Summary

Config =

Hash containing various configuration options.

Since:

  • 0.1

{
  # The name of the default command to invoke when no command is specified.
  :default_command => :default,

  # The name of the default method to invoke.
  :default_method => :index,

  # The amount of spaces to insert before each option.
  :indent => '  ',

  # The format for each header for help topics, options, etc.
  :heading => "\n%s:\n",

  # When set to true Shebang will raise an exception for errors instead of
  # just printing a message.
  :raise => true
}
Commands =

Hash containing the names of all commands and their classes.

Since:

  • 0.1

{}
Version =

:nodoc:

Since:

  • 0.1

'0.1'

Class Method Summary (collapse)

Class Method Details

+ (Object) error(message)

Raises an exception or prints a regular error message to STDERR based on the :raise configuration option.

Parameters:

  • message (String)

    The message to display.

Author:

  • Yorick Peterse

Since:

  • 0.1



96
97
98
99
100
101
102
# File 'lib/shebang.rb', line 96

def error(message)
  if Config[:raise] === true
    raise(Error, message)
  else
    abort "\e[0;31mError:\e[0m #{message}"
  end
end

+ (Object) run(argv = ARGV)

Runs a command based on the command line arguments. If no command is given this method will try to invoke the default command.

Parameters:

  • argv (Array) (defaults to: ARGV)

    Array containing the command line arguments to parse.

Author:

  • Yorick Peterse

Since:

  • 0.1



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/shebang.rb', line 49

def run(argv = ARGV)
  self.error("No commands have been registered") if Commands.empty?

  command = Config[:default_command].to_sym
  method  = Config[:default_method].to_sym

  if !argv.empty?
    # Get the command name
    if argv[0][0] != '-' and Commands.key?(argv[0].to_sym)
      command = argv.delete_at(0).to_sym
    end
  end

  if Commands.key?(command)
    klass = Commands[command].new

    # Get the method to call.
    if argv[0] and argv[0][0] != '-' and klass.respond_to?(argv[0].to_sym)
      method = argv.delete_at(0).to_sym
    end

    # Parse the arguments and prepare all the options.
    argv = klass.parse(argv)

    # Call the method and pass the commandline arguments to it.
    if klass.respond_to?(method)
      if klass.class.instance_method(method).arity != 0
        klass.send(method, argv)
      else
        klass.send(method)
      end
    else
      error("The command #{command} does not have a #{method}() method")
    end
  else
    error("The command #{command} does not exist")
  end
end