Sha256: cc68ac58e5e8a3f3d83c0a1b39486cc0aae0cf2065e5ecad8d8bcf14b674fa24

Contents?: true

Size: 1.06 KB

Versions: 19

Compression:

Stored size: 1.06 KB

Contents

module Cri::CoreExtensions

  module String

    # Word-wraps and indents the string.
    #
    # +width+:: The maximal width of each line. This also includes indentation,
    #           i.e. the actual maximal width of the text is width-indentation.
    #
    # +indentation+:: The number of spaces to indent each wrapped line.
    def wrap_and_indent(width, indentation)
      # Split into paragraphs
      paragraphs = self.split("\n").map { |p| p.strip }.reject { |p| p == '' }

      # Wrap and indent each paragraph
      paragraphs.map do |paragraph|
        # Initialize
        lines = []
        line = ''

        # Split into words
        paragraph.split(/\s/).each do |word|
          # Begin new line if it's too long
          if (line + ' ' + word).length >= width
            lines << line
            line = ''
          end

          # Add word to line
          line += (line == '' ? '' : ' ' ) + word
        end
        lines << line

        # Join lines
        lines.map { |l| ' '*indentation + l }.join("\n")
      end.join("\n\n")
    end

  end

end

Version data entries

19 entries across 19 versions & 4 rubygems

Version Path
shu-san-scripts-0.3.0 lib/SANStore/cri/core_ext/string.rb
shu-san-scripts-0.2.3 lib/SANStore/cri/core_ext/string.rb
shu-san-scripts-0.2.1 lib/SANStore/cri/core_ext/string.rb
shu-san-scripts-0.1.0 lib/SANStore/cri/core_ext/string.rb
shu-san-scripts-0.0.2 lib/SANStore/cri/core_ext/string.rb
nanoc3-3.0.9 vendor/cri/lib/cri/core_ext/string.rb
nanoc3-3.0.8 vendor/cri/lib/cri/core_ext/string.rb
nanoc3-3.0.7 vendor/cri/lib/cri/core_ext/string.rb
nanoc3-3.0.6 vendor/cri/lib/cri/core_ext/string.rb
nanoc3-3.0.5 vendor/cri/lib/cri/core_ext/string.rb
nanoc3-3.0.4 vendor/cri/lib/cri/core_ext/string.rb
nanoc3-3.0.3 vendor/cri/lib/cri/core_ext/string.rb
nanoc3-3.0.2 vendor/cri/lib/cri/core_ext/string.rb
cri-1.0.1 lib/cri/core_ext/string.rb
nanoc3-3.0.1 vendor/cri/lib/cri/core_ext/string.rb
nanoc3-3.0.0 vendor/cri/lib/cri/core_ext/string.rb
nanoc-2.2.2 vendor/cri/lib/cri/core_ext/string.rb
nanoc-2.2.1 vendor/cri/lib/cri/core_ext/string.rb
nanoc-2.2 vendor/cri/lib/cri/core_ext/string.rb