module SvgDrawer::Utils::Text

Constants

DEFAULT_WORD_PATTERN

Public Instance Methods

truncate(text, maxlen, trailer = '...') click to toggle source
# File lib/svg_drawer/utils/text.rb, line 17
def truncate(text, maxlen, trailer = '...')
  return text unless text.length > maxlen
  raise if maxlen < trailer.length
  text.slice(0, maxlen - trailer.length).concat(trailer)
end
word_wrap(txt, maxlen, word_pattern = DEFAULT_WORD_PATTERN) click to toggle source

Wrap on any word delimiter, but consider a word followed by a single delimiter and a space as unwrappable (e.g. end of sentence)

If word itself is longer than max line length, force-wrap it on any char (effectively slicing it at maxlen)

# File lib/svg_drawer/utils/text.rb, line 30
def word_wrap(txt, maxlen, word_pattern = DEFAULT_WORD_PATTERN)
  words = txt.scan(word_pattern)

  words.each_with_object(['']) do |word, lines|
    last = lines.last
    wordlen = word.rstrip.length

    if wordlen > maxlen
      lines.concat(word.scan(/.{1,#{maxlen}}/))
    elsif last != '' && last.length + wordlen > maxlen
      lines << word
    else
      lines.last << word
    end
  end.delete_if(&:empty?).each(&:strip!)
end