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?



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

def duplicate_output_to
  @duplicate_output_to
end

Class Method Details

.assert_enabled!Object

: -> void

Raises:



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

def assert_enabled!
  raise NotEnabled unless enabled?
end

.current_idObject

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



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

def current_id
  Thread.current[:cliui_output_id]
end

.disableObject

: -> bool



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

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

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

.enableObject

: -> bool



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

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)


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

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

.ensure_activatedObject

TODO: remove this : -> void



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

def ensure_activated
  enable unless enabled?
end

.with_enabled(&block) ⇒ Object

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



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

def with_enabled(&block)
  enable
  yield
ensure
  disable
end

.with_id(on_streams:, &block) ⇒ Object

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



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

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