Class: Verse::Wrapping

Inherits:
Object
  • Object
show all
Defined in:
lib/verse/wrapping.rb

Overview

A class responsible for text wrapping

Constant Summary collapse

DEFAULT_WIDTH =
80

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text, options = {}) ⇒ Wrapping

Initialize a Wrapping

Parameters:

  • text (String)

    the text to be wrapped

  • options (Hash) (defaults to: {})

    @option options [Symbol] :padding the desired spacing



17
18
19
20
# File 'lib/verse/wrapping.rb', line 17

def initialize(text, options = {})
  @text       = text
  @line_width = options.fetch(:line_width) { DEFAULT_WIDTH }
end

Class Method Details

.wrap(text, wrap_at, options = {}) ⇒ Object

Wrap a text into lines no longer than wrap_at



25
26
27
# File 'lib/verse/wrapping.rb', line 25

def self.wrap(text, wrap_at, options = {})
  new(text, options).wrap(wrap_at)
end

Instance Method Details

#wrap(wrap_at = DEFAULT_WIDTH) ⇒ Object

Wrap a text into lines no longer than wrap_at length. Preserves existing lines and existing word boundaries.

Examples:

wrapping = Verse::Wrapping.new "Some longish text"

wrapping.wrap(8)
# => >Some
     >longish
     >text


41
42
43
44
45
46
47
48
49
# File 'lib/verse/wrapping.rb', line 41

def wrap(wrap_at = DEFAULT_WIDTH)
  if text.length < wrap_at.to_i || wrap_at.to_i.zero?
    return text
  end
  ansi_stack = []
  text.split(NEWLINE, -1).map do |paragraph|
    format_paragraph(paragraph, wrap_at, ansi_stack)
  end * NEWLINE
end