Sha256: 04127971a7accf31f0cb7e849d83ae6a946f2be29da513135a85fb557a690345

Contents?: true

Size: 1.47 KB

Versions: 13

Compression:

Stored size: 1.47 KB

Contents

module Vedeu
  class Wordwrap
    class << self
      def this(value, options = {})
        new(value, options).reformat
      end
    end

    def initialize(value, options = {})
      @value   = value
      @options = options || {}
    end

    def reformat
      return pruned if prune?
      wordwrapped
    end

    def wordwrapped
      processed = []
      value.split(/\n/).map do |unprocessed|
        line_length = 0
        reformatted = []

        unprocessed.split(/\s/).map do |word|
          word_length = word.length + 1

          if (line_length += word_length) >= maximum_width
            line_length = word_length
            processed   << reformatted
            reformatted = []
          end

          reformatted << word
        end

        processed << reformatted
      end

      output(processed)
    end

    private

    attr_reader :value, :options

    def output(paragraph)
      paragraph.reduce([]) do |output, line|
        output << line.join(' ')
      end.join("\n")
    end

    def pruned
      return value if value.size <= pruned_width
      [
        value.chomp.slice(0..pruned_width),
        '...',
        Esc.reset
      ].join
    end

    def pruned_width
      maximum_width - 3
    end

    def prune?
      options.fetch(:prune)
    end

    def maximum_width
      options.fetch(:width)
    end

    def options
      defaults.merge!(@options)
    end

    def defaults
      {
        width: 70,
        prune: false
      }
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
vedeu-0.0.23 lib/vedeu/output/wordwrap.rb
vedeu-0.0.22 lib/vedeu/output/wordwrap.rb
vedeu-0.0.21 lib/vedeu/output/wordwrap.rb
vedeu-0.0.20 lib/vedeu/output/wordwrap.rb
vedeu-0.0.19 lib/vedeu/output/wordwrap.rb
vedeu-0.0.18 lib/vedeu/output/wordwrap.rb
vedeu-0.0.17 lib/vedeu/output/wordwrap.rb
vedeu-0.0.16 lib/vedeu/output/wordwrap.rb
vedeu-0.0.15 lib/vedeu/output/wordwrap.rb
vedeu-0.0.14 lib/vedeu/output/wordwrap.rb
vedeu-0.0.13 lib/vedeu/output/wordwrap.rb
vedeu-0.0.12 lib/vedeu/output/wordwrap.rb
vedeu-0.0.11 lib/vedeu/output/wordwrap.rb