Class: JsDuck::Shortener
- Inherits:
-
Object
- Object
- JsDuck::Shortener
- Includes:
- Util::Singleton
- Defined in:
- lib/jsduck/shortener.rb
Overview
Little helper for shortening text
Instance Attribute Summary collapse
-
#max_length ⇒ Object
Maximum length for text that doesn’t get shortened.
Instance Method Summary collapse
-
#first_sentence(str) ⇒ Object
Returns the first sentence inside a string.
-
#initialize ⇒ Shortener
constructor
A new instance of Shortener.
-
#shorten(input) ⇒ Object
Shortens text.
-
#too_long?(input) ⇒ Boolean
Returns true when input should get shortened.
Methods included from Util::Singleton
Constructor Details
#initialize ⇒ Shortener
Returns a new instance of Shortener.
15 16 17 |
# File 'lib/jsduck/shortener.rb', line 15 def initialize @max_length = 120 end |
Instance Attribute Details
#max_length ⇒ Object
Maximum length for text that doesn’t get shortened. The accessor is used for testing purposes only.
13 14 15 |
# File 'lib/jsduck/shortener.rb', line 13 def max_length @max_length end |
Instance Method Details
#first_sentence(str) ⇒ Object
Returns the first sentence inside a string.
44 45 46 |
# File 'lib/jsduck/shortener.rb', line 44 def first_sentence(str) str.sub(/\A(.+?(\.|。))\s.*\Z/mu, "\\1") end |
#shorten(input) ⇒ Object
Shortens text
116 chars is also where ext-doc makes its cut, but unlike ext-doc we only make the cut when there’s more than 120 chars.
This way we don’t get stupid expansions like:
Blah blah blah some text...
expanding to:
Blah blah blah some text.
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/jsduck/shortener.rb', line 32 def shorten(input) sent = first_sentence(Util::HTML.(input).strip) # Use u-modifier to correctly count multi-byte characters chars = sent.scan(/./mu) if chars.length > @max_length chars[0..(@max_length-4)].join + "..." else sent + " ..." end end |
#too_long?(input) ⇒ Boolean
Returns true when input should get shortened.
49 50 51 52 53 54 |
# File 'lib/jsduck/shortener.rb', line 49 def too_long?(input) stripped = Util::HTML.(input).strip # for sentence v/s full - compare byte length # for full v/s max - compare char length first_sentence(stripped).length < stripped.length || stripped.scan(/./mu).length > @max_length end |