Veerasundaravel's Ruby on Rails Weblog

August 3, 2010

Wrap a very long url

Some time we may need to display a long url in our web-page. On that case, it will break the design as we can’t display a string in multiple lines with there is no space between.

Yes obviously, a link can’t have any space in between them. We can add <br> tag in between url, but the problem is while you are copying the URL, you still need to modify the copied content before using it in browser address bar. So I tried the following solution.

<wbr> tag

Write a helper method as follows:


#This method is used to split the longer urls into few lines.
#We added the tag <wbr> on a regular interval of a string.

def custom_word_wrap(text, max_width=10)
return nil if text.blank?
(text.length < max_width) ?
text :
text.scan(/.{1,#{max_width}}/).join(“<wbr>”)
end

In your view file:

<%= custom_word_wrap(@url_to_display, 55) %>

Outputs:

<%= @url_to_display %>

http://localhost.com/sssssssssssssssssssssoooooooooooooooooommmmmmmmmmmmmmmmmmmmmeeeeeeeeeeeeeeeeeeeeeeeeeebbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaadddddddddddddddduuuuuuuuuuuuuuuurrrrrrrrrrrrrrlllllllllllllllll

<%= custom_word_wrap(@url_to_display, 55) %>

http://localhost.com/sssssssssssssssssssssooooooo
ooooooooooommmmmmmmmmmmmmmmmmmmmeeeeeeeeeee
eeeeeeeeeeeeeeebbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaa
aaaadddddddddddddddduuuuuuuuuuuuuuuurrrrrrrrrrrrrrlllllllllllllllll

Advertisements

3 Comments »

  1. Pretty great post. I simply stumbled upon your weblog and wished to mention that I’ve truly loved surfing around your weblog posts. In any case I’ll be subscribing
    on your feed and I’m hoping you write again soon!

    Comment by reputable website — September 14, 2012 @ 3:28 pm

  2. Greetings! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My website looks weird when browsing from my iphone. I’m trying to find a template or plugin that
    might be able to correct this problem. If you have any suggestions, please share.
    Thank you!

    Comment by Selene — September 21, 2012 @ 10:15 pm

  3. It’s very trouble-free to find out any matter on web as compared to books, as I found this piece of writing at this website.

    Comment by champions league 2013 — May 7, 2013 @ 3:52 am


RSS feed for comments on this post. TrackBack URI

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

%d bloggers like this: