class Heroics::CLI

Public Class Methods

new(name, commands, output) click to toggle source

Instantiate a CLI for an API described by a JSON schema.

@param name [String] The name of the CLI. @param schema [Schema] The JSON schema describing the API. @param client [Client] A client generated from the JSON schema. @param output [IO] The stream to write to.

# File lib/heroics/cli.rb, line 10
def initialize(name, commands, output)
  @name = name
  @commands = commands
  @output = output
end

Public Instance Methods

run(*parameters) click to toggle source

Run a command.

@param parameters [Array] The parameters to use when running the

command.  The first parameters is the name of the command and the
remaining parameters are passed to it.
# File lib/heroics/cli.rb, line 21
def run(*parameters)
  name = parameters.shift
  if name.nil? || name == 'help'
    if command_name = parameters.first
      command = @commands[command_name]
      command.usage
    else
      usage
    end
  else
    command = @commands[name]
    if command.nil?
      @output.write("There is no command called '#{name}'.\n")
    else
      command.run(*parameters)
    end
  end
end

Private Instance Methods

usage() click to toggle source

Write usage information to the output stream.

# File lib/heroics/cli.rb, line 43
    def usage
      if @commands.empty?
        @output.write 'No commands are available.'
        return
      end

      @output.write <<-USAGE
Usage: #{@name} <command> [<parameter> [...]] [<body>]

Help topics, type "#{@name} help <topic>" for more details:

USAGE

      name_width = @commands.keys.max_by { |key| key.size }.size
      @commands.sort.each do |name, command|
        name = name.ljust(name_width)
        description = command.description
        @output.puts("  #{name}    #{description}")
      end
    end