Reputation: 1700
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. How can I do that in Ruby (on Rails)?
Upvotes: 4
Views: 1170
Reputation: 7487
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.
Upvotes: 0
Reputation: 169543
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
Upvotes: 5
Reputation: 14716
Assuming your words are delimited by a space, you can do something like this.
stories.split(' ').slice(0,50).join(' ')
Upvotes: 6