Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActiveSupport's String#truncate fails with Regexp as separator

#6732

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

Reported by ast · April 20th, 2011 @ 05:44 PM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

No comments yet.