Module: FlossFunding::Terminal

Defined in:
lib/floss_funding/terminal_helpers.rb

Overview

Helpers for interacting with terminal characteristics

Class Method Summary collapse

Class Method Details

.apply_width!(table) ⇒ Object

Apply detected width to a Terminal::Table instance when possible.



45
46
47
48
49
50
51
# File 'lib/floss_funding/terminal_helpers.rb', line 45

def apply_width!(table)
  cols = columns
  table.style = {:width => cols} if cols && cols > 0
  table
rescue StandardError
  table
end

.columns ⇒ Object

Determine current terminal columns, checking tput each time for up-to-date size.
Returns an Integer or nil when unknown.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/floss_funding/terminal_helpers.rb', line 10

def columns
  cols = nil
  # Prefer tput, over TTY::Screen.width (from the tty-screen gem), for cross-platform compatibility
  begin
    out = %x(tput cols 2>/dev/null).to_s.strip
    cols = Integer(out) unless out.empty?
  rescue StandardError
    # ignore
  end

  # Fallback to COLUMNS env
  if cols.nil? || cols <= 0
    begin
      env_cols = ENV["COLUMNS"]
      cols = Integer(env_cols) if env_cols && !env_cols.to_s.empty?
    rescue StandardError
      # ignore
    end
  end

  # Fallback to IO.console only if it looks like a TTY context
  if (cols.nil? || cols <= 0) && $stdout.tty?
    begin
      require "io/console"
      _, c = IO.console.winsize
      cols = c if c && c > 0
    rescue StandardError
      # ignore
    end
  end

  (cols.is_a?(Integer) && cols > 0) ? cols : nil
end