Module: HaveAPI::CLI::ExampleFormatter

Defined in:
lib/haveapi/cli/example_formatter.rb

Class Method Summary collapse

Class Method Details

.example_param(name, value, desc) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/haveapi/cli/example_formatter.rb', line 27

def self.example_param(name, value, desc)
  option = name.to_s.dasherize

  case desc[:type]
    when 'Boolean'
      value ? "--#{option}" : "--no-#{option}"

    else
      "--#{option} #{example_value(value)}"
  end
end

.example_value(v) ⇒ Object



39
40
41
# File 'lib/haveapi/cli/example_formatter.rb', line 39

def self.example_value(v)
  (v.is_a?(String) && (v.empty? || v.index(' '))) ? "\"#{v}\"" : v
end

.format_examples(cli, action, out = $>) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/haveapi/cli/example_formatter.rb', line 3

def self.format_examples(cli, action, out = $>)
  action.examples.each do |example|
    out << ' > ' << example[:title] << ":\n" unless example[:title].empty?

    # request
    out << "$ #{$0} #{action.resource_path.join('.')} #{action.name}"

    params = example[:request][action.namespace(:input).to_sym]

    if params
      out << ' --' unless params.empty?

      params.each do |k, v|
        out << ' ' << example_param(k, v, action.param_description(:input, k))
      end
    end

    out << "\n"

    # response
    cli.format_output(action, example[:response], out)
  end
end