Class: TerminalSize::TerminalSize

Inherits:
Object
  • Object
show all
Defined in:
lib/scaling/terminal_size.rb

Overview

class to extract the terminal dimension of the the terminal which called the executing script

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTerminalSize

initialization



19
20
21
# File 'lib/scaling/terminal_size.rb', line 19

def initialize
  read_terminal_size
end

Instance Attribute Details

#columnsInteger (readonly)

Returns the number of lines of the used terminal.

Returns:

  • (Integer)

    the number of lines of the used terminal



14
15
16
# File 'lib/scaling/terminal_size.rb', line 14

def columns
  @columns
end

#linesInteger (readonly)

Returns the number of fields per row of the used terminal.

Returns:

  • (Integer)

    the number of fields per row of the used terminal



16
17
18
# File 'lib/scaling/terminal_size.rb', line 16

def lines
  @lines
end

Instance Method Details

#command_exists?(command) ⇒ Boolean (private)

method to check if the given command can be executed

Parameters:

  • command (String)

    the provided command string

Returns:

  • (Boolean)

    true: command can be used, false if not



61
62
63
64
65
# File 'lib/scaling/terminal_size.rb', line 61

def command_exists?(command)
  ENV['PATH'].split(File::PATH_SEPARATOR).any? { |d|
    File.exist?(File.join(d, command))
  }
end

#detect_terminal_sizeArray (private)

method to read the terminal dimension, using different shell programs

Returns:

  • (Array)

    the read values for the terminal dimension



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/scaling/terminal_size.rb', line 39

def detect_terminal_size
  # take informations directly from ENV variable
  if (ENV['COLUMNS'] =~ /^\d+$/) && (ENV['LINES'] =~ /^\d+$/)
    [ENV['COLUMNS'].to_i, ENV['LINES'].to_i]
  # take informations from tput command
  elsif ((RUBY_PLATFORM =~ /java/ || (!STDIN.tty? && ENV['TERM'])) &&
          command_exists?('tput'))
    [`tput cols`.to_i, `tput lines`.to_i]
  # take informations from stty command
  elsif (STDIN.tty? && command_exists?('stty'))
    `stty size`.scan(/\d+/).map { |s| s.to_i }.reverse
  else
    nil
  end
rescue StandardError
  puts ' Error: could not determine correct terminal size'.red
  nil
end

#read_terminal_sizeObject

method to determine the terminal dimension



24
25
26
27
28
29
30
31
32
33
# File 'lib/scaling/terminal_size.rb', line 24

def read_terminal_size
  values = detect_terminal_size
  if (values != nil)
    @columns = values[0]
    @lines = values[1]
  else
    raise NoMethodError, ' Error: terminal size cannot be retrieved on' \
                         ' this system'.red
  end
end