Class: Brut::CLI::Output

Inherits:
Object
  • Object
show all
Defined in:
lib/brut/cli/output.rb

Overview

An IO-like class that provides user-helpful output, to be used in place of puts and a logger. This is not replaceable for an IO.

The problem this solves is allowing your CLI app to be clutter-free in the user's terminal, but to not hide information unnecessarily or make it unclear where the output is coming from. Your CLI should use this class (or the methods that proxy to it, see Brut::CLI::Commands::BaseCommand) for all output and logging.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io:, app_name:) ⇒ Output

Create a wrapper for the given IO that will use the given prefix

Parameters:

  • io (IO)

    an IO where output should be sent, for example $stdout.

  • app_name (String)

    the name of the app that would be using this to generate output.



24
25
26
27
28
# File 'lib/brut/cli/output.rb', line 24

def initialize(io:, app_name:)
  @io          = io
  @app_name    = app_name
  @sync_status = @io.sync
end

Instance Attribute Details

#ioObject (readonly)

Returns the value of attribute io.



17
18
19
# File 'lib/brut/cli/output.rb', line 17

def io
  @io
end

#prefixObject (readonly)

Returns the value of attribute prefix.



18
19
20
# File 'lib/brut/cli/output.rb', line 18

def prefix
  @prefix
end

Class Method Details

.from_io(io_or_output) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/brut/cli/output.rb', line 8

def self.from_io(io_or_output)
  case io_or_output
  in Brut::CLI::Output
    io_or_output
  else
    self.new(io: io_or_output, app_name: $0)
  end
end

Instance Method Details

#flushObject

Flush the underlying IO.



50
51
52
53
# File 'lib/brut/cli/output.rb', line 50

def flush
  @io.flush
  self
end

#printf(format_string, *objects) ⇒ Object

Prints a string via printf, using the prefix. This is useful for communciating to a human, but you need more power for formatting than is afforded by #puts.



45
46
47
# File 'lib/brut/cli/output.rb', line 45

def printf(format_string,*objects)
  @io.printf(format_string,*objects)
end

#puts(*objects) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/brut/cli/output.rb', line 31

def puts(*objects)
  if objects.empty?
    objects << ""
  end
  objects.each do |object|
    @io.puts(object)
  end
  nil
end