Class: SensuCli::Pretty

Inherits:
Object
  • Object
show all
Defined in:
lib/sensu-cli/pretty.rb

Class Method Summary collapse

Class Method Details

.clean(thing) ⇒ Object



34
35
36
37
# File 'lib/sensu-cli/pretty.rb', line 34

def self.clean(thing)
  thing = thing.gsub("\n",'/\n') if thing.is_a?(String)
  thing
end

.count(res) ⇒ Object



29
30
31
32
# File 'lib/sensu-cli/pretty.rb', line 29

def self.count(res)
  res.is_a?(Hash) ? count = res.length : count = res.count
  puts "#{count} total items".color(:yellow) if count
end


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/sensu-cli/pretty.rb', line 6

def self.print(res)
  if !res.empty?
    if res.is_a?(Hash)
      res.each do |key,value|
        puts "#{key}:  ".color(:cyan) + "#{value}".color(:green)
      end
    elsif res.is_a?(Array)
      res.each do |item|
        puts "-------".color(:yellow)
        if item.is_a?(Hash)
          item.each do |key,value|
            puts "#{key}:  ".color(:cyan) + "#{value}".color(:green)
          end
        else
          puts item.to_s.color(:cyan)
        end
      end
    end
  else
    puts "no values for this request".color(:cyan)
  end
end

.table(res) ⇒ Object



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
# File 'lib/sensu-cli/pretty.rb', line 39

def self.table(res)
  if !res.empty?
    if res.is_a?(Array)
      keys = res.map{|item| item.keys}.flatten.uniq.sort

      # Remove fields with spaces (breaks awkage)
      keys.select! do |key|
        res.none?{|item| item[key].to_s.include?(' ')}
      end

      # Find max value lengths
      value_lengths = {}
      keys.each do |key|
        max_value_length = res.map{|item| item[key].to_s.length}.max
        value_lengths[key] = [max_value_length, key.length].max
      end

      # Print header
      format = keys.map {|key| "%-#{value_lengths[key]}s"}.join(' ')
      puts sprintf(format, *keys)

      # Print value rows
      res.each do |item|
        if item.is_a?(Hash)
          values = keys.map {|key| item[key]}
          format = keys.map {|key| "%-#{value_lengths[key]}s"}.join(' ')
          puts sprintf(format, *values)
        else
          puts item.to_s.color(:cyan)
        end
      end
    end
  else
    puts "no values for this request".color(:cyan)
  end
end