class Airbrussh::Console

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.

Attributes

config[R]
output[R]

Public Class Methods

new(output, config=Airbrussh.configuration) click to toggle source
# File lib/airbrussh/console.rb, line 15
def initialize(output, config=Airbrussh.configuration)
  @output = output
  @config = config
end

Public Instance Methods

<<(string)
Alias for: write
console_width() click to toggle source
# File lib/airbrussh/console.rb, line 62
def console_width
  width = case (truncate = config.truncate)
          when :auto
            IO.console.winsize.last if @output.tty?
          when Integer
            truncate
          end

  width if width.to_i > 0
end
print_line(obj="") click to toggle source

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.

strip_ascii_color(string) click to toggle source
# 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) click to toggle source
# 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) click to toggle source

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

# File lib/airbrussh/console.rb, line 36
def write(string)
  output.write(string || "")
end
Also aliased as: <<

Private Instance Methods

color_enabled?() click to toggle source
# File lib/airbrussh/console.rb, line 75
def color_enabled?
  case config.color
  when true
    true
  when :auto
    ENV["SSHKIT_COLOR"] || @output.tty?
  else
    false
  end
end
to_utf8(string) click to toggle source
# File lib/airbrussh/console.rb, line 92
def to_utf8(string)
  string.force_encoding("ASCII-8BIT")
        .encode("UTF-8", :invalid => :replace, :undef => :replace)
end
utf8_supported?(string) click to toggle source
# File lib/airbrussh/console.rb, line 86
def utf8_supported?(string)
  string.encode("UTF-8").valid_encoding?
rescue Encoding::UndefinedConversionError
  false
end