How can i truncate a text to the closest position with rails 3 whithout cut in the middle of a word?
For exemple, I have the string :
"Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum."
If i cut it, i want to cut like this :
"Praesent commodo cursus magna, vel scelerisque nisl ..."
And not :
"Praesent commodo cursus magna, vel scelerisque nisl conse..."
If you pass in a separator to the truncate method it will perform a natural word break instead of truncating at a middle of a word
Something like this should work (vary the length to whatever you want to remove it altogether if you want the default of 30 characters):
truncate("Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.", :length => 17, :separator => ' ')
More information about the options you can have in truncate can be found in the Documentation
Starting Rails 4.2
there is a new ActiveSupport
method called string#truncate_words
. It truncates a string by number of words which makes it impossible to have a cut in the middle of a word.
'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
which returns
"And they found that many... (continued)"
Truncate is a great option, but if you want to have complete word detection, regex is your solution. I would recommend something like this:
string.match(/^.{0,30}\b/)[0]
Or you can put this in a function
def shorten(string, count)
string.match(/^.{0,#{count}}\b/)[0]
end
According to Rails documentation, you can pass regex into the truncate method, like so:
'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
Both of these options offer far better word boundary detection than passing in a space character into the truncate method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With