Class: Airbrussh::Console

Inherits:
Object
  • Object
show all
Defined in:
lib/airbrussh/console.rb

Overview

Helper class that wraps an IO object and provides methods for truncating output, assuming the IO object represents a console window.

This is useful for writing log messages that will typically show up on an ANSI color-capable console. When a console is not present (e.g. when running on a CI server) the output will gracefully degrade.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(output, config = Airbrussh.configuration) ⇒ Console

Returns a new instance of Console.



15
16
17
18
# File 'lib/airbrussh/console.rb', line 15

def initialize(output, config=Airbrussh.configuration)
  @output = output
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



13
14
15
# File 'lib/airbrussh/console.rb', line 13

def config
  @config
end

#outputObject (readonly)

Returns the value of attribute output.



13
14
15
# File 'lib/airbrussh/console.rb', line 13

def output
  @output
end

Instance Method Details

#console_widthObject



62
63
64
65
66
67
68
69
70
71
# File 'lib/airbrussh/console.rb', line 62

def console_width
  width = case (truncate = config.truncate)
          when :auto
            IO.console.winsize.last if @output.tty? && IO.console
          when Integer
            truncate
          end

  width if width.to_i > 0
end

Writes to the IO after first truncating the output to fit the console width. If the underlying IO is not a TTY, ANSI colors are removed from the output. A newline is always added. Color output can be forced by setting the SSHKIT_COLOR environment variable.



24
25
26
27
28
29
30
31
32
# File 'lib/airbrussh/console.rb', line 24

def print_line(obj="")
  string = obj.to_s

  string = truncate_to_console_width(string) if console_width
  string = strip_ascii_color(string) unless color_enabled?

  write(string + "\n")
  output.flush
end

#strip_ascii_color(string) ⇒ Object



55
56
57
58
59
60
# File 'lib/airbrussh/console.rb', line 55

def strip_ascii_color(string)
  string ||= ""
  string = to_utf8(string) unless string.valid_encoding?

  string.gsub(/\033\[[0-9;]*m/, "")
end

#truncate_to_console_width(string) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/airbrussh/console.rb', line 41

def truncate_to_console_width(string)
  string = (string || "").rstrip
  ellipsis = utf8_supported?(string) ? "" : "..."
  width = console_width

  if strip_ascii_color(string).length > width
    width -= ellipsis.length
    string.chop! while strip_ascii_color(string).length > width
    string << "#{ellipsis}\e[0m"
  else
    string
  end
end

#write(string) ⇒ Object Also known as: <<

Writes directly through to the IO with no truncation or color logic. No newline is added.



36
37
38
# File 'lib/airbrussh/console.rb', line 36

def write(string)
  output.write(string || "")
end