Had the same problem so I wrote this method: put it into your helpers and application.rb. There might be a cleaner way using Regexp or scan... this uses String.split() str = the string to split len = longest length of each piece char = character to split them with # - split a long string into smaller pieces, at most "len" characters # in length. "len" default is 10, if not supplied. # - returns the split string def split_str(str=nil, len=10, char=" ") len = 10 if len < 1 work_str = str.to_s.split(//) if str return_str = "" i = 0 if work_str work_str.each do |s| if (s == char || i == len) return_str += char return_str += s if s != char i = 0 else return_str += s i += 1 end end end return_str end
} Had the same problem so I wrote this method: put it into your helpers } and application.rb. There might be a cleaner way using Regexp or } scan... this uses String.split() } str = the string to split } len = longest length of each piece [19 lines of code elided]
Shorter, cleaner, more efficient, whitespace-preserving, and uses the HTML wbr tag (which is a hint for word breaking and is supported well in FF and IE, though poorly in Safari and not at all in Opera):
def split_str(str, len = 10) fragment = /.{#{len}}/ str.split(/(\s+)/).map! { |word| (/\s/ === word) ? word : word.gsub(fragment, '\0<wbr />') }.join end
Note that this will put a wbr tag at the end of words which have a length evenly divisible by len; these can be removed with another gsub if desired, but they are harmless. Note also that Rails does some annoying rewriting of HTML output, and changes <wbr /> into <wbr> for no good reason. This doesn't affect how browsers render things, but it does mean the results are no longer XHTML-compliant.
--Greg
Hey, I said there's probobly a better way to do it. Thanks Greg. I'll put your slimmed down version in.
Bart