Module: Kennel::Console

Defined in:
lib/kennel/console.rb

Defined Under Namespace

Classes: TeeIO

Constant Summary collapse

COLORS =
{ red: 31, green: 32, yellow: 33, cyan: 36, magenta: 35, default: 0 }.freeze

Class Method Summary collapse

Class Method Details

.ask?(question) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
26
# File 'lib/kennel/console.rb', line 18

def ask?(question)
  Kennel.err.printf color(:red, "#{question} -  press 'y' to continue: ", force: true)
  begin
    Kennel.in.gets.chomp == "y"
  rescue Interrupt # do not show a backtrace if user decides to Ctrl+C here
    Kennel.err.print "\n"
    exit 1
  end
end

.capture_stderrObject



43
44
45
46
47
48
49
50
# File 'lib/kennel/console.rb', line 43

def capture_stderr
  old = Kennel.err
  Kennel.err = StringIO.new
  yield
  Kennel.err.string
ensure
  Kennel.err = old
end

.capture_stdoutObject



34
35
36
37
38
39
40
41
# File 'lib/kennel/console.rb', line 34

def capture_stdout
  old = Kennel.out
  Kennel.out = StringIO.new
  yield
  Kennel.out.string
ensure
  Kennel.out = old
end

.color(color, text, force: false) ⇒ Object



28
29
30
31
32
# File 'lib/kennel/console.rb', line 28

def color(color, text, force: false)
  return text unless force || Kennel.out.tty?

  "\e[#{COLORS.fetch(color)}m#{text}\e[0m"
end

.tee_outputObject



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/kennel/console.rb', line 52

def tee_output
  old_stdout = Kennel.out
  old_stderr = Kennel.err
  capture = StringIO.new
  Kennel.out = TeeIO.new([capture, Kennel.out])
  Kennel.err = TeeIO.new([capture, Kennel.err])
  yield
  capture.string
ensure
  Kennel.out = old_stdout
  Kennel.err = old_stderr
end