Module: Doing::StringTruncate
- Included in:
- String
- Defined in:
- lib/doing/string/truncate.rb
Overview
String truncation
Instance Method Summary collapse
-
#trunc(len, ellipsis: '...') ⇒ Object
Truncate to nearest word.
- #trunc!(len, ellipsis: '...') ⇒ Object
-
#truncend(len, ellipsis: '...') ⇒ Object
Truncate from middle to end at nearest word.
- #truncend!(len, ellipsis: '...') ⇒ Object
-
#truncmiddle(len, ellipsis: '...') ⇒ Object
Truncate string in the middle, separating at nearest word.
- #truncmiddle!(len, ellipsis: '...') ⇒ Object
Instance Method Details
#trunc(len, ellipsis: '...') ⇒ Object
Truncate to nearest word
13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/doing/string/truncate.rb', line 13 def trunc(len, ellipsis: '...') return self if length <= len total = 0 res = [] split(/ /).each do |word| break if total + 1 + word.length > len total += 1 + word.length res.push(word) end res.join(' ') + ellipsis end |
#trunc!(len, ellipsis: '...') ⇒ Object
28 29 30 |
# File 'lib/doing/string/truncate.rb', line 28 def trunc!(len, ellipsis: '...') replace trunc(len, ellipsis: ellipsis) end |
#truncend(len, ellipsis: '...') ⇒ Object
Truncate from middle to end at nearest word
37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/doing/string/truncate.rb', line 37 def truncend(len, ellipsis: '...') return self if length <= len total = 0 res = [] split(/ /).reverse.each do |word| break if total + 1 + word.length > len total += 1 + word.length res.unshift(word) end ellipsis + res.join(' ') end |
#truncend!(len, ellipsis: '...') ⇒ Object
52 53 54 |
# File 'lib/doing/string/truncate.rb', line 52 def truncend!(len, ellipsis: '...') replace truncend(len, ellipsis: ellipsis) end |
#truncmiddle(len, ellipsis: '...') ⇒ Object
Truncate string in the middle, separating at nearest word
62 63 64 65 66 67 68 69 |
# File 'lib/doing/string/truncate.rb', line 62 def truncmiddle(len, ellipsis: '...') return self if length <= len len -= (ellipsis.length / 2).to_i half = (len / 2).to_i start = trunc(half, ellipsis: ellipsis) finish = truncend(half, ellipsis: '') start + finish end |
#truncmiddle!(len, ellipsis: '...') ⇒ Object
71 72 73 |
# File 'lib/doing/string/truncate.rb', line 71 def truncmiddle!(len, ellipsis: '...') replace truncmiddle(len, ellipsis: ellipsis) end |