Module: CLI::UI::StdoutRouter

Defined in:
lib/cli/ui/stdout_router.rb

Defined Under Namespace

Classes: Capture, Writer

Constant Summary collapse

WRITE_WITHOUT_CLI_UI =
:write_without_cli_ui
NotEnabled =
Class.new(StandardError)

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.duplicate_output_toObject

: io_like?



312
313
314
# File 'lib/cli/ui/stdout_router.rb', line 312

def duplicate_output_to
  @duplicate_output_to
end

Class Method Details

.assert_enabled!Object

: -> void

Raises:



335
336
337
# File 'lib/cli/ui/stdout_router.rb', line 335

def assert_enabled!
  raise NotEnabled unless enabled?
end

.current_idObject

: -> Hash[Symbol, (String | io_like)]?



330
331
332
# File 'lib/cli/ui/stdout_router.rb', line 330

def current_id
  Thread.current[:cliui_output_id]
end

.disableObject

: -> bool



368
369
370
371
372
373
374
# File 'lib/cli/ui/stdout_router.rb', line 368

def disable
  return false unless enabled?($stdout) && enabled?($stderr)

  deactivate($stdout)
  deactivate($stderr)
  true
end

.enableObject

: -> bool



354
355
356
357
358
359
360
# File 'lib/cli/ui/stdout_router.rb', line 354

def enable
  return false if enabled?($stdout) || enabled?($stderr)

  activate($stdout, :stdout)
  activate($stderr, :stderr)
  true
end

.enabled?(stream = $stdout) ⇒ Boolean

: (?io_like stream) -> bool

Returns:

  • (Boolean)


363
364
365
# File 'lib/cli/ui/stdout_router.rb', line 363

def enabled?(stream = $stdout)
  stream.respond_to?(WRITE_WITHOUT_CLI_UI)
end

.ensure_activatedObject

TODO: remove this : -> void



349
350
351
# File 'lib/cli/ui/stdout_router.rb', line 349

def ensure_activated
  enable unless enabled?
end

.with_enabled(&block) ⇒ Object

: [T] { -> T } -> T



340
341
342
343
344
345
# File 'lib/cli/ui/stdout_router.rb', line 340

def with_enabled(&block)
  enable
  yield
ensure
  disable
end

.with_id(on_streams:, &block) ⇒ Object

: [T] (on_streams: Array) { (String id) -> T } -> T



315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/cli/ui/stdout_router.rb', line 315

def with_id(on_streams:, &block)
  require 'securerandom'
  id = format('%05d', rand(10**5))
  Thread.current[:cliui_output_id] = {
    id: id,
    streams: on_streams.map do |stream|
      stream #: as io_like
    end,
  }
  yield(id)
ensure
  Thread.current[:cliui_output_id] = nil
end