How to truncate text in Ruby on Rails
It's really simple to truncate text in Rails, just pass the function the text, the max number of characters you want to show and a truncate string you want to display instead of the last 3 characters.
truncate(category.description, 40, "...")
About
Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
4 comments made
You’d probably be happier with something like this, which will cut off text at a word boundary. You can put it in your application helper to use it in all your views.
def snippet(thought)
wordcount = 10
thought.split[0..(wordcount-1)].join(” “) + (thought.split.size > wordcount ? ”...” : ””)
end
@Chris thanks, I’m gunna use this. However, I modified it so that the wordcount is passable as a parameter:
def snippet(thought, wordcount) thought.split[0..(wordcount-1)].join(" ") +(thought.split.size > wordcount ? "..." : "") endAlso, just an fyi, when I pasted your code into Textmate it preserved the fancy quotes, which gave me about 30 seconds of WTF?
Try this one out, the number in brackets is the number of chars to match:
thought.gsub(/^(.{10}[\w.])(.)/) {$2.empty? ? $1 : $1 + ’...’}
It doesn’t break words and adds ’...’ if necessary. Check out www.golark.com and click submit to really be impressed with the power of regex.
Great, it took the asterisks out. Replace the a’s in the following string with asterisks:
thought.gsub(/^(.{10}[\w.]a)(.a)/) {$2.empty? ? $1 : $1 + ’...’}
Got something to say?