Unobstrusive word_wrap aka split_after for Ruby / Rails

Evil users often write something like “SomeThingNewAndGreat,use,it aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa” just to annoy us developers who try to get their content into a 50x100px div (at least I suspect it…).

Usage
(Use it after truncating, since it adds additional characters)

#!invisible char between 6 and 7!
"12345 12345678".split_after(3) == "12345 123456​78"
"12345 12345678".split_after(6, :with=>'<br />') == "12345 123456<br />78"

Code

  # splits to long words after max chars with invisible "zero-length-space"
  # UTF8 char that should display in all browsers
  # http://www.fileformat.info/info/unicode/char/200b/index.htm
  def split_after(max, options={})
    zero_length_space = '​' #aka ​
    options[:with] ||= zero_length_space

    split(/ /).map do |part|
      part = part.mb_chars
      if part.length > max
        part[0...max] + options[:with] + part[max..-1].to_s.split_after(max)
      else
        part
      end
    end * ' '
  end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s