Class: CLI::UI::StdoutRouter::Capture

Inherits:
Object
  • Object
show all
Defined in:
lib/cli/ui/stdout_router.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*block_args, with_frame_inset: true, &block) ⇒ Capture


86
87
88
89
90
# File 'lib/cli/ui/stdout_router.rb', line 86

def initialize(*block_args, with_frame_inset: true, &block)
  @with_frame_inset = with_frame_inset
  @block_args = block_args
  @block = block
end

Instance Attribute Details

#stderrObject (readonly)

Returns the value of attribute stderr


92
93
94
# File 'lib/cli/ui/stdout_router.rb', line 92

def stderr
  @stderr
end

#stdoutObject (readonly)

Returns the value of attribute stdout


92
93
94
# File 'lib/cli/ui/stdout_router.rb', line 92

def stdout
  @stdout
end

Class Method Details

.with_stdin_maskedObject


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/cli/ui/stdout_router.rb', line 65

def self.with_stdin_masked
  @m.synchronize do
    if @active_captures.zero?
      @saved_stdin = $stdin
      $stdin, w = IO.pipe
      $stdin.close
      w.close
    end
    @active_captures += 1
  end

  yield
ensure
  @m.synchronize do
    @active_captures -= 1
    if @active_captures.zero?
      $stdin = @saved_stdin
    end
  end
end

Instance Method Details

#runObject


94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/cli/ui/stdout_router.rb', line 94

def run
  require 'stringio'

  StdoutRouter.assert_enabled!

  out = StringIO.new
  err = StringIO.new

  prev_frame_inset = Thread.current[:no_cliui_frame_inset]
  prev_hook = Thread.current[:cliui_output_hook]

  self.class.with_stdin_masked do
    Thread.current[:no_cliui_frame_inset] = !@with_frame_inset
    Thread.current[:cliui_output_hook] = ->(data, stream) do
      case stream
      when :stdout then out.write(data)
      when :stderr then err.write(data)
      else raise
      end
      false # suppress writing to terminal
    end

    begin
      @block.call(*@block_args)
    ensure
      @stdout = out.string
      @stderr = err.string
    end
  end
ensure
  Thread.current[:cliui_output_hook] = prev_hook
  Thread.current[:no_cliui_frame_inset] = prev_frame_inset
end