-
Notifications
You must be signed in to change notification settings - Fork 3
Usage Example
CLIs can be built by using a Executable as a mixin, or by subclassing
Executable::Command. Methods seemlessly handle command-line options.
Writer methods (those ending in '=') correspond to options and query
methods (those ending in '?') modify them to be boolean switches.
For example, here is a simple "Hello, World!" commandline tool.
require 'executable'
class HelloCommand
include Executable
# Say it in uppercase?
def loud=(bool)
@loud = bool
end
#
def loud?
@loud
end
# Show this message.
def help!
cli.show_help
exit
end
alias :h! :help1
# Say hello.
def call(name)
name = name || 'World'
str = "Hello, #{name}!"
str = str.upcase if loud?
puts str
end
endTo make the command available on the command line, add an executable to your project calling the #execute or #run methods.
#!usr/bin/env ruby
require 'hello.rb'
HelloCommand.runIf we named this file hello, set its execute flag and made it available
on our systems $PATH, then:
$ hello
Hello, World!
$ hello John
Hello, John!
$ hello --loud John
HELLO, JOHN!
Executable can also generate help text for commands.
$ hello --help
USAGE: hello [options]
Say hello.
--loud Say it in uppercase?
--help Show this message
If you look back at the class definition you can see it's pulling
comments from the source to provide descriptions. It pulls the
description for the command itself from the #call method.