Skip to content
Ruby command-line option parser for the lazy
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
lib
test
tools
README.md
metacli.gemspec

README.md

MetaCLI

Ruby command-line option parser for the lazy

Allows for defining commands as methods receiving command-line arguments and options as positional and keyword arguments, respectively.

Instead of having to explicitly declare available commands and their arguments and options, dynamically extrapolates those from regular method definitions. Generates concise usage messages upon --help and invalid calls.

Command descriptions may be specified as method documentation.

Example

$ ruby my_script.rb foo bar --baz --qux=123

would call:

my_obj.cmd_foo("bar", baz: true, qux: "123")

Used in:

Install

Gemfile:

gem 'metacli', github: 'Roman2K/metacli'

Usage

require 'metacli'

class MyApp
  def initialize(verbose: false)
    @verbose = verbose
  end

  def cmd_hello(firstname, lastname=nil)
    name = [firstname, lastname].compact * " "
    puts "Hello #{name}"
  end

  # Prints its argument
  def cmd_echo(msg, shout: false)
    msg = msg.upcase if shout
    puts msg
  end

  private def puts(msg)
    $stderr.puts "writing to stdout" if @verbose
    $stdout.puts msg
  end
end

cli = MetaCLI.new ARGV
verbose = cli.opts.delete :verbose  # --verbose is a global flag. Delete it so
                                    # it won't be passed to the command
app = MyApp.new verbose: verbose
cli.run app

Output

Global usage:

$ ruby my_script.rb -h
Usage: my_script.rb hello|echo [options]

Commands:

  hello firstname [lastname]
  echo msg --[no-]shout · Prints its argument

Command usage:

$ ruby my_script.rb hello -h
Usage: my_script.rb hello firstname [lastname]

Command usage (with description):

$ ruby my_script.rb echo -h
Usage: my_script.rb echo msg --[no-]shout

Prints its argument

Successful run:

$ ruby my_script.rb hello Bob
Hello Bob

Successful run (with global option):

$ ruby my_script.rb hello Bob Sponge --verbose
writing to stdout
Hello Bob Sponge

Invalid call (command not specified):

$ ruby my_script.rb
(metacli)/metacli.rb:37:in `run': Usage: my_script.rb hello|echo [options] (ArgumentError)
	from my_script.rb:29:in `<main>'

Invalid call (missing argument):

$ ruby my_script.rb hello
(metacli)/metacli.rb:54:in `rescue in run': Usage: my_script.rb hello firstname [lastname] (ArgumentError)
	from (metacli)/metacli.rb:51:in `run'
	from my_script.rb:29:in `<main>'
You can’t perform that action at this time.