Class: Vop::ShellFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/vop/shell/shell_formatter.rb

Instance Method Summary collapse

Instance Method Details

#analyze(request, response) ⇒ Object


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
# File 'lib/vop/shell/shell_formatter.rb', line 7

def analyze(request, response)
  data = response.result

  if request.command.show_options[:display_type]
    # TODO check that display_type is valid
    request.command.show_options[:display_type]
  else
    if data.is_a? Array
      first_row = data.first
      if first_row.is_a? Hash
        :table
      elsif first_row.is_a? Entity
        :entity_list
      else
        :list
      end
    elsif data.is_a? Hash
      :hash
    elsif data.is_a? Entity
      :entity
    else
      :raw
    end
  end
end

#format(request, response, display_type) ⇒ Object


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/vop/shell/shell_formatter.rb', line 33

def format(request, response, display_type)
  data = response.result
  command = request.command
  show_options = command.show_options

  result = case display_type
  when :table
    columns_to_display =
      if show_options[:columns]
        show_options[:columns]
      else
        # TODO this is not optimal - what if the second row has more keys than the first?
        first_row = data.first
        first_row.keys
      end

    # add an index column
    column_headers = [ '#' ] + columns_to_display

    # array of hashes -> array of arrays
    rearranged = []
    data.each do |row|
      values = [ ]
      columns_to_display.each do |key|
        values << (row[key.to_s] || row[key.to_sym])
      end
      rearranged << values
    end

    unless show_options.include?(:sort) && show_options[:sort] == false
      rearranged.sort_by! { |row| row.first || "" }
    end

    # add the index column after sorting
    rearranged.each_with_index do |row, index|
      row.unshift index
    end

    Terminal::Table.new(
      rows: rearranged,
      headings: column_headers
    )
  when :list
    data.join("\n")
  when :hash
    data.map do |k,v|
      "#{k} : #{v}"
    end.join("\n")
  when :entity_list
    data.sort_by { |e| e.id }.map do |entity|
      attributes = entity.data.sort_by do |x|

      end.map do |key, value|
        if key == entity.key
          nil
        else
          "#{key} : #{value}"
        end
      end.compact.join("\n  ")
      "[#{entity.type}] #{entity.id}\n  #{attributes}"
    end.join("\n")
  when :entity
    entity = data
    "[#{entity.type}] #{entity.id}"
  when :raw
    data
  when :data
    data.pretty_inspect
  else
    raise "unknown display type #{display_type}"
  end

  result
end