Module: Cork::TextWrapper

Defined in:
lib/cork/text_wrapper.rb

Class Method Summary collapse

Class Method Details

.strip_heredoc(string) ⇒ String

Returns Lifted straigth from Actionview. Thanks Guys!.

Returns:

  • (String)

    Lifted straigth from Actionview. Thanks Guys!



66
67
68
69
70
71
72
# File 'lib/cork/text_wrapper.rb', line 66

def strip_heredoc(string)
  if min = string.scan(/^[ \t]*(?=\S)/).min
    string.gsub(/^[ \t]{#{min.size}}/, '')
  else
    string
  end
end

.word_wrap(line, line_width) ⇒ String

Returns Lifted straigth from Actionview. Thanks Guys!.

Returns:

  • (String)

    Lifted straigth from Actionview. Thanks Guys!



58
59
60
# File 'lib/cork/text_wrapper.rb', line 58

def word_wrap(line, line_width)
  line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip
end

.wrap_formatted_text(string, indent = 0, width = 80) ⇒ String

Returns Wraps a formatted string (e.g. markdown) by stripping heredoc indentation and wrapping by word to the terminal width taking into account a maximum one, and indenting the string. Code lines (i.e. indented by four spaces) are not wrapped.

Parameters:

  • string (String)

    The string to format.

  • indent (Fixnum) (defaults to: 0)

    The number of spaces to insert before the string.

  • width (Fixnum) (defaults to: 80)

    The width to use to format the string if the terminal is too wide.

Returns:

  • (String)

    Wraps a formatted string (e.g. markdown) by stripping heredoc indentation and wrapping by word to the terminal width taking into account a maximum one, and indenting the string. Code lines (i.e. indented by four spaces) are not wrapped.



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/cork/text_wrapper.rb', line 20

def wrap_formatted_text(string, indent = 0, width = 80)
  paragraphs = strip_heredoc(string).split("\n\n")
  paragraphs = paragraphs.map do |paragraph|
    if paragraph.start_with?(' ' * 4)
      paragraphs.gsub!(/\n/, "\n#{' ' * indent}")
    else
      paragraph = wrap_with_indent(paragraph, indent, width)
    end
    paragraph.insert(0, ' ' * indent).rstrip
  end
  paragraphs.join("\n\n")
end

.wrap_with_indent(string, indent = 0, width = 80) ⇒ String

Returns Wraps a string to the terminal width taking into account the given indentation.

Parameters:

  • string (String)

    The string to indent.

  • indent (Fixnum) (defaults to: 0)

    The number of spaces to insert before the string.

  • width (Fixnum) (defaults to: 80)

    The width to use when formatting the string in the terminal

Returns:

  • (String)

    Wraps a string to the terminal width taking into account the given indentation.



47
48
49
50
51
52
# File 'lib/cork/text_wrapper.rb', line 47

def wrap_with_indent(string, indent = 0, width = 80)
  full_line = string.gsub("\n", ' ')
  available_width = width - indent
  space = ' ' * indent
  word_wrap(full_line, available_width).split("\n").join("\n#{space}")
end