Class: LLM::Paint::IO

Inherits:
Object
  • Object
show all
Defined in:
lib/llm/paint/io.rb

Overview

The IO class wraps an IO so that the text written to it is wrapped in the escape sequences a terminal understands, but only when the wrapped IO is a terminal and LLM::Paint is enabled. Otherwise the text is written unchanged.

Examples:

io = LLM::Paint::IO.new(io: $stdout)
io.write("hello", :blue, :bold)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io:, color: nil) ⇒ LLM::Paint::IO

Parameters:

  • io (IO) —

    The IO to write to

  • color (Boolean, nil) (defaults to: nil) —

    Enables or disables color. When it is nil, color is detected from the IO and $NO_COLOR.



27
28
29
30
# File 'lib/llm/paint/io.rb', line 27

def initialize(io:, color: nil)
  @io = io
  @color = color.nil? ? LLM::Paint.detect(io) : !!color
end

Instance Attribute Details

#io ⇒ IO (readonly)

Returns The IO that is wrapped.

Returns:

  • (IO) —

    The IO that is wrapped



18
19
20
# File 'lib/llm/paint/io.rb', line 18

def io
  @io
end

Instance Method Details

#color? ⇒ Boolean

Returns True when this IO writes color.

Returns:

  • (Boolean) —

    True when this IO writes color



35
36
37
# File 'lib/llm/paint/io.rb', line 35

def color?
  @color
end

#color=(color)

This method returns an undefined value.

Enables or disables color, and when it is given nil it goes back to detecting what the IO supports.

Parameters:

  • color (Boolean, nil)


44
45
46
# File 'lib/llm/paint/io.rb', line 44

def color=(color)
  @color = color.nil? ? LLM::Paint.detect(@io) : !!color
end

#write(text, *options) ⇒ Integer

Writes text to the wrapped IO. The text is wrapped in the escape sequences that represent the given colors and effects when color is enabled, and written unchanged otherwise.

Parameters:

  • text (String, #to_s) —

    The text to write

  • options (Array<Symbol>) —

    A foreground color, a background color, and/or an effect

Returns:

  • (Integer) —

    The number of bytes written



59
60
61
62
63
64
65
# File 'lib/llm/paint/io.rb', line 59

def write(text, *options)
  if color?
    @io.write(LLM::Paint[text, *options])
  else
    @io.write(text.to_s)
  end
end

#puts(text, *options) ⇒ Integer

Write with a newline.

Parameters:

  • text (String, #to_s) —

    The text to write

  • options (Array<Symbol>) —

    A foreground color, a background color, and/or an effect

Returns:

  • (Integer) —

    The number of bytes written



71
72
73
# File 'lib/llm/paint/io.rb', line 71

def puts(text, *options)
  write("#{text}\n", *options)
end