Sha256: 2a4e13ab9627cb38f9d2d389d5c18ba89f86ea535281def310f54ed4487ea88c

Contents?: true

Size: 1.46 KB

Versions: 23

Compression:

Stored size: 1.46 KB

Contents

module Vedeu
  class Wordwrap
    def self.this(value, options = {})
      new(value, options).reformat
    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
      if value.size <= pruned_width
        value

      else
        [
          value.chomp.slice(0..pruned_width),
          '...'
        ].join

      end
    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

23 entries across 23 versions & 1 rubygems

Version Path
vedeu-0.1.9 lib/vedeu/support/wordwrap.rb
vedeu-0.1.8 lib/vedeu/support/wordwrap.rb
vedeu-0.1.7 lib/vedeu/support/wordwrap.rb
vedeu-0.1.6 lib/vedeu/support/wordwrap.rb
vedeu-0.1.5 lib/vedeu/support/wordwrap.rb
vedeu-0.1.4 lib/vedeu/support/wordwrap.rb
vedeu-0.1.3 lib/vedeu/support/wordwrap.rb
vedeu-0.1.2 lib/vedeu/support/wordwrap.rb
vedeu-0.1.1 lib/vedeu/support/wordwrap.rb
vedeu-0.1.0 lib/vedeu/support/wordwrap.rb
vedeu-0.0.42 lib/vedeu/support/wordwrap.rb
vedeu-0.0.41 lib/vedeu/support/wordwrap.rb
vedeu-0.0.40 lib/vedeu/support/wordwrap.rb
vedeu-0.0.39 lib/vedeu/support/wordwrap.rb
vedeu-0.0.38 lib/vedeu/support/wordwrap.rb
vedeu-0.0.37 lib/vedeu/support/wordwrap.rb
vedeu-0.0.36 lib/vedeu/support/wordwrap.rb
vedeu-0.0.35 lib/vedeu/support/wordwrap.rb
vedeu-0.0.34 lib/vedeu/support/wordwrap.rb
vedeu-0.0.33 lib/vedeu/support/wordwrap.rb