Module: SvgDrawer::Utils::Text
- Defined in:
- lib/svg_drawer/utils/text.rb
Constant Summary collapse
- DEFAULT_WORD_PATTERN =
/ [[:word:]]+ # chars [^[:word:]] # delimiter \s? # optional space (?![^[:word:]]) # not followed by delimiter | [[:word:]]+ # chars | [^[:word:]] # delimiter /x
Class Method Summary collapse
- .truncate(text, maxlen, trailer = '...') ⇒ Object
-
.word_wrap(txt, maxlen, word_pattern = DEFAULT_WORD_PATTERN) ⇒ Object
Wrap on any word delimiter, but consider a word followed by a single delimiter and a space as unwrappable (e.g. end of sentence).
Class Method Details
.truncate(text, maxlen, trailer = '...') ⇒ Object
17 18 19 20 21 |
# 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) ⇒ Object
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)
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# 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 |