An unopinionated universal commandline interface for Ruby. Given a collection of Objects, provides a reasonable CLI with automatic help generation.
Ruby has a number of excellent gems for building commandline applications. They range in complexity, but share a common approach: defining an interface to some objects.
But… your objects already have interfaces: their public methods
.
instacli
adopts this perspective when building a CLI.
gem install instacli
Imagine we have an EchoClass
that implements an echo(string)
method that
returns string
. Something like this:
class EchoClass
def echo(string)
string
end
end
We can add a CLI for it like so:
require 'instacli'
boring_object = EchoClass.new
cli = InstaCLI.new boring: boring_object
cli.execute(*ARGV)
Assuming this code is in cli.rb
, and cli.rb
is executable, we can use this
CLI as follows:
./cli.rb boring echo foo
And it will output foo
to STDOUT
.
Using the same EchoClass
, we can add help like so:
class CLI < InstaCLI::CLI
include InstaCLI::Help
end
cli = CLI.new boring: boring_object
cli.execute(*ARGV)
Now running cli.rb
with --help
, like so:
./cli.rb --help boring echo
Will print the following:
NAME: cli boring echo - CommandLine Interface USAGE: cli boring echo <string>
A single InstaCLI
can expose as many objects as you like. Just give it a
hash, mapping the command names you want to use, to the objects they expose.
mapping = {
foo: SomeObject.new,
bar: AnotherObject.new
}
InstaCLI::CLI.new mapping
Any public methods
on an object will be exposed as subcommands (ignoring
any generic methods from Object
itself).
Disabled by default, can be enabled with include InstaCLI::Help
.
The parameters of a method are used to generate usage documentation,
following the common convention of <required>
and [optional]
.
If a method raises an ArgumentError
, a usage notice will be displayed,
outlining the correct usage.
Disabled by default, can be enabled with include InstaCLI::Demuxing
.
When enabled, the name the program was invoked with is read as the command to execute.
instacli
is available under the MIT License. See LICENSE.txt
for the full text.