Imported from Lighthouse. Original ticket at: http://rails.lighthouseapp.com/projects/8994/tickets/6732
Created by ast - 2011-04-20 16:44:09 UTC
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
44 substr = sep
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..."