Want to show the first 50 or 60 words of a text box in a ruby?

I have a text box for stories and you want to show the first few lines - say, the first 50 words of this field - on the snapshot page. How can I do this in Ruby (on Rails)?

+3
source share
3 answers

Basically the same as Aaron Hinny's answer , but will try to keep 3 complete sentences (then truncate to 50 words if those sentences were too long)

def truncate(text, max_sentences = 3, max_words = 50)
  # Take first 3 setences (blah. blah. blah)
  three_sentences = text.split('. ').slice(0, max_sentences).join('. ')
  # Take first 50 words of the above
  shortened = three_sentences.split(' ').slice(0, max_words).join(' ')
  return shortened # bah, explicit return is evil
end

Also, if there is HTML in this text, my answer is "Truncate Markdown?" may be useful

+4
source

, , - .

stories.split(' ').slice(0,50).join(' ')
+6

Use something very similar in a Rails application to extend ("monkey patch") the base class String.

I created lib/core_extensions.rbone that contains:

class String
  def to_blurb(word_count = 30)
    self.split(" ").slice(0, word_count).join(" ")
  end
end

Then I created config/initializers/load_extensions.rbone that contains:

require 'core_extensions'

Now I have a method to_blurb()for all my String objects in a Rails application.

0
source

Source: https://habr.com/ru/post/1705866/


All Articles