Module: Tuxedo::Tty
Class Method Summary collapse
- .color_enabled? ⇒ Boolean
-
.def_color(name, code) ⇒ Object
Generates color methods.
Instance Method Summary collapse
- #capture_stderr ⇒ Object
- #capture_stdout ⇒ Object
- #escape(code) ⇒ Object
-
#terminal_size ⇒ Object
Returns [width, height] of terminal when detected, nil if not detected.
- #terminal_size_available? ⇒ Boolean
- #with_color(true_or_false = true) ⇒ Object
Class Method Details
.color_enabled? ⇒ Boolean
4 5 6 |
# File 'lib/tuxedo/tty.rb', line 4 def color_enabled? @color_enabled end |
.def_color(name, code) ⇒ Object
Generates color methods.
Fore each generated method:
When called without an argument:
Returns the terminal escape code.
When called with an argument:
Returns the argument#to_s, wrapped in both
the color escape code and reset escape code.
Examples:
red #=> "\e[31m"
red("Blah") #=> "\e[31mBlah\e[0m"
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/tuxedo/tty.rb', line 20 def def_color(name, code) class_eval <<-CODE, __FILE__, __LINE__ + 1 def #{name}(text=(default_arg=true;nil)) if Tty.color_enabled? if default_arg "#{escape(code)}" else "#{escape(code)}\#{text}#{escape(0)}" end else text.to_s end end CODE end |
Instance Method Details
#capture_stderr ⇒ Object
79 80 81 82 83 84 85 86 |
# File 'lib/tuxedo/tty.rb', line 79 def capture_stderr out = StringIO.new $stderr = out yield return out ensure $stderr = STDERR end |
#capture_stdout ⇒ Object
70 71 72 73 74 75 76 77 |
# File 'lib/tuxedo/tty.rb', line 70 def capture_stdout out = StringIO.new $stdout = out yield return out ensure $stdout = STDOUT end |
#escape(code) ⇒ Object
45 46 47 |
# File 'lib/tuxedo/tty.rb', line 45 def escape(code) "\033[#{code}m" if Tty.color_enabled? end |
#terminal_size ⇒ Object
Returns [width, height] of terminal when detected, nil if not detected. Think of this as a simpler version of Highline’s Highline::SystemExtensions.terminal_size() github.com/cldwalker/hirb/blob/0df53628bd07845feed43030477b65106e75c7dd/lib/hirb/util.rb#L55-73
95 96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/tuxedo/tty.rb', line 95 def terminal_size if (ENV['COLUMNS'] =~ /^\d+$/) && (ENV['LINES'] =~ /^\d+$/) [ENV['COLUMNS'].to_i, ENV['LINES'].to_i] elsif (RUBY_PLATFORM =~ /java/ || (!STDIN.tty? && ENV['TERM'])) && command_exists?('tput') [`tput cols`.to_i, `tput lines`.to_i] elsif STDIN.tty? && command_exists?('stty') `stty size`.scan(/\d+/).map { |s| s.to_i }.reverse else nil end rescue nil end |
#terminal_size_available? ⇒ Boolean
88 89 90 |
# File 'lib/tuxedo/tty.rb', line 88 def terminal_size_available? !!terminal_size end |
#with_color(true_or_false = true) ⇒ Object
62 63 64 65 66 67 68 |
# File 'lib/tuxedo/tty.rb', line 62 def with_color(true_or_false=true) old_color_enabled = Tty.color_enabled? Tty.send(:color_enabled=, true_or_false) yield ensure Tty.send(:color_enabled=, old_color_enabled) end |