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



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/haveapi/cli/example_formatter.rb', line 34

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



46
47
48
# File 'lib/haveapi/cli/example_formatter.rb', line 46

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
26
27
28
29
30
31
32
# 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]

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

      params.each do |k, v|
        desc = action.param_description(:input, k)
        next unless desc

        out << ' ' << example_param(k, v, desc)
      end
    end

    out << "\n"

    # response
    cli.format_output(
      action,
      { action.namespace(:output).to_sym => example[:response] },
      out
    )
  end
end