SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Tuesday, May 19, 2009

Customized truncate helper in rails

In Rails truncate helper will truncates a given text after a given :length if text is longer than :length (defaults to 30).The problem is that when we truncate the string by character or word, it will cutoff the text mid-word and creating open tag problems.

So i started referring some of the articles Pretty truncate helper and customized my own helper like this

def truncate_words(text, length = 30, string = "...")
return if text.nil?
l = text.index(/\s/,length)
text.chars.length > length ? text[0,l] + string : text + string
end

Example



>> text
=> "In unprecedented market conditions, Murex retained its top position in Risk's 2008 technology rankings. However, Thomson Reuters and Algorithmics are close behind, demonstrating that, despite the financial crisis, competition among software vendors remains as fierce as ever. By Clive Davidson, with research by Xiao-Long Chen"
>> helper.truncate(text,130)
=> "In unprecedented market conditions, Murex retained its top position in Risk's 2008 technology rankings. However, Thomson Reuter..."
>> helper.truncate_words(text,130)
=> "In unprecedented market conditions, Murex retained its top position in Risk's 2008 technology rankings. However, Thomson Reuters and..."

Just note the example if we use truncate with length 130 then reuters seems to cuttoff to reuter, then the next customized helper with 130 length does not cuttoff the word reuters
If we want to use the code without writing in helpers then we can try like this

<%truncate_string = "..." %>
<%g= text.index(/\s/,130)%>
<%=text.chars.length > 130 ? text.description[0,g] + truncate_string : text + truncate_string%>
here 130 is the length of the string to truncate

No comments :

Post a Comment