ActiveSupport's String#truncate fails with Regexp as separator #1049

Closed
lighthouse-import opened this Issue May 16, 2011 · 0 comments

Projects

None yet

1 participant

@lighthouse-import

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
 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment