Long words killing HTML display

Hi, I’m trying to use word_wrap to prevent long
‘aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa…’ from kill my display
tables in HTML. Problem is that word_wrap doesn’t dissect these long
words and expects to only break them if it sees a ‘\n’. Does anybody
know if Rails has a helper to do this, not that it is hard to implement
on my own but jsut wondering if there’s something really clean that
takes care of this and anything more.

Thanks.

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

Hey, I said there’s probobly a better way to do it. Thanks Greg. I’ll
put your slimmed down version in.

Bart

On Wed, Nov 08, 2006 at 12:37:32AM -0800, Bart wrote:
} 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’)
}.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 into for no good reason. This
doesn’t affect how browsers render things, but it does mean the results
are
no longer XHTML-compliant.

–Greg

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs