Class: Heroics::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/heroics/command.rb

Instance Method Summary collapse

Constructor Details

#initialize(cli_name, link_schema, client, output) ⇒ Command

Instantiate a command.

Parameters:

  • cli_name (String)

    The name of the CLI.

  • link_schema (LinkSchema)

    The schema for the underlying link this command represents.

  • client (Client)

    The client to use when making requests.

  • output (IO)

    The stream to write output to.



11
12
13
14
15
16
# File 'lib/heroics/command.rb', line 11

def initialize(cli_name, link_schema, client, output)
  @cli_name = cli_name
  @link_schema = link_schema
  @client = client
  @output = output
end

Instance Method Details

#descriptionObject

The command description.



24
25
26
# File 'lib/heroics/command.rb', line 24

def description
  @link_schema.description
end

#nameObject

The command name.



19
20
21
# File 'lib/heroics/command.rb', line 19

def name
  "#{@link_schema.pretty_resource_name}:#{@link_schema.pretty_name}"
end

#run(*parameters) ⇒ Object

Run the command and write the results to the output stream.

Parameters:

  • parameters (Array)

    The parameters to pass when making a request to run the command.



57
58
59
60
61
62
63
64
65
66
# File 'lib/heroics/command.rb', line 57

def run(*parameters)
  resource_name = @link_schema.resource_name
  name = @link_schema.name
  result = @client.send(resource_name).send(name, *parameters)
  result = result.to_a if result.instance_of?(Enumerator)
  if result && !result.instance_of?(String)
    result = MultiJson.dump(result, pretty: true)
  end
  @output.puts(result) unless result.nil?
end

#usageObject

Write usage information to the output stream.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/heroics/command.rb', line 29

def usage
  parameters = @link_schema.parameters.map { |parameter| "<#{parameter}>" }
  parameters = parameters.empty? ? '' : " #{parameters.join(' ')}"
  example_body = @link_schema.example_body
  body_parameter = example_body.nil? ? '' : ' <body>'
  @output.write <<-USAGE
Usage: #{@cli_name} #{name}#{parameters}#{body_parameter}

Description:
  #{description}
USAGE
  if example_body
    example_body = MultiJson.dump(example_body, pretty: true)
    example_body = example_body.lines.map do |line|
      "  #{line}"
    end.join
    @output.write <<-USAGE

Body example:
#{example_body}
USAGE
  end
end