views:

253

answers:

3

I have a stories text field and want to show the first few lines say the first 50 words of that field in a snapshot page.In ruby(on rails) How do i do that??

+5  A: 

Assuming your words are delimited by a space, you can do something like this.

stories.split(' ').slice(0,50).join(' ')
Aaron Hinni
+3  A: 

Mostly the same as Aaron Hinni's answer, but will try and keep 3 full sentences (then truncate to 50 words, if it's the 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 this text has any HTML, my answer on "Truncate Markdown?" might be of use

dbr
I give +1 for this, good idea ;-)
Aaron Hinni
A: 

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

I created lib/core_extensions.rb which contains:

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

I then created config/initializers/load_extensions.rb which contains:

require 'core_extensions'

Now I have the to_blurb() method on all my String objects in the Rails application.

mlambie