This project is archived and is in readonly mode.
ActiveSupport's String#truncate fails with Regexp as separator
Reported by ast | April 20th, 2011 @ 05:44 PM
Trying to integrate ActiveSupport into an existing non-Rails system, I unintentionally discovered AS 3.0.5 defines its own #truncate method. Unfortunately, for word boundaries, this doesn't take regular expressions since it assumes that the separator will be a string, e.g:
44 stop = options[:separator] ?
45 (chars.rindex(options[:separator].mb_chars, length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission
Since it doesn't say explicitly that strings are required and this to me is most useful on sentence breaks, e.g. regex-based sets of punctuation.
To allow #truncate to use regex objects as separators, I've made the following change which seems to do what I'd expect:
41 if(sep = options[:separator]) && sep.is_a?(String)
42 substr = sep.mb_chars
43 else
44 substr = sep
45 end
46
47 length_with_room_for_omission = length - options[:omission].mb_chars.length
48 chars = text.mb_chars
49 stop = options[:separator] ?
50 (chars.rindex(substr, length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission
It would be cool if this might be approved and included in a future version.
Code that doesn't work in 3.0.5:
>> "The quick brown fox jumped over the lazy dog. Wasn't he grand?".truncate(50, :separator => /[?\.!]/)
=> "The quick brown fox jumped over the lazy dog..."
Cheers,
ast
No comments found
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>