views:

408

answers:

2

In my rails project I have the following code

auto_link( h( wrap_long_string(post.text,50)  )).gsub(/\n/,"<br />")

wrap_long_string is defined as:

  def wrap_long_string(txt,col = 20)
    txt.gsub(/(.{1,#{col}})( +|$\n?)|(.{1,#{col}})/,
      "\\1\\3\n")
  end

This code is meant to display user entered text while preventing users from messing up the layout of the page (by entering a very long non-breaking string for example).

However, the act of breaking up long non-breaking strings also prevents the auto_link helper from working.

What I would like to do is to have the following text:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=ZGF&amp;q=example&amp;btnG=Search

Be turned into something like:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<br/>aaaaaaaaaa <a href='http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=ZGF&amp;q=example&amp;btnG=Search'&gt;http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=ZGF&amp;q=example&amp;btnG=Search&lt;/a&gt;
+1  A: 

If you have control over the order these are applied in, I'd suggested running the text through the auto-link helper and then through the long text breaker (and make that 'smart' enough to not count text in html tags as text :)). That should create the links, and I belive you can have
in between tags without any ill consequences :)

workmad3
A: 

Alternatively, you could define your own auto_link (use the existing code in text_helper.rb as a model) to first scan for urls (and for emails), do the substitution, find the indices of where you've made substitutions, and then break the line in places that don't fall within those indices.

This should only require the existing autolink code along with a coupe of calls to index() and length().

klochner