Greg Séguin
Greg Séguin

Reputation: 47

Truncate sentences in rails?

I've got a helper that I'm using to truncate strings in Rails, and it works great when I truncate sentences that end in periods. How should I modify the code to also truncate sentences when they end in question marks or exclamation points?

def smart_truncate(s, opts = {})
    opts = {:words => 12}.merge(opts)
    if opts[:sentences]
      return s.split(/\.(\s|$)+/).reject{ |s| s.strip.empty? }[0, opts[:sentences]].map{|s| s.strip}.join('. ') + '...'
    end
    a = s.split(/\s/) # or /[ ]+/ to only split on spaces
    n = opts[:words]
    a[0...n].join(' ') + (a.size > n ? '... (more)' : '')
end

Thanks!!!

Upvotes: 0

Views: 1015

Answers (1)

Oss
Oss

Reputation: 4322

You have the truncate method

'Once upon a time in a world far far away'.truncate(27, separator: /\s/, ommission: "....")

which will return "Once upon a time in a..."


And if you need to truncate by number of words instead then use the newly introduced truncate_words (since Rails 4.2.2)

'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')

which returns

"And they found that many... (continued)"

Upvotes: 2

Related Questions