Skip to content

Instantly share code, notes, and snippets.

@coryschires
Created June 3, 2010 20:40
Show Gist options
  • Save coryschires/424449 to your computer and use it in GitHub Desktop.
Save coryschires/424449 to your computer and use it in GitHub Desktop.
sentence_truncate helper
# Based on http://stackoverflow.com/questions/1293573/rails-smart-text-truncation
def sentence_truncate(string, num_sentences, enforce_max_length=true)
pattern = /[\.\?\!]{1,}\s/
matches = string.scan(pattern)
sentences = string.split(pattern)
num_sentences = matches.length if matches.length < num_sentences
truncated_sentence = sentences[0...num_sentences].map do |sentence|
sentence << matches[sentences.index(sentence)]
end.join("").chop
# optionally enforce max length in case of really long sentences
if enforce_max_length
max_length = num_sentences*100
truncated_sentence = truncate(truncated_sentence, :length => max_length) if truncated_sentence.length > max_length
end
truncated_sentence
end
# rspec test
it "should split a text block on sentences" do
text = "I am a sentence about radio station 95.5 WHOT. What a hot station! I love that one. Don't you? Well, onto other things, my friend. Like the fourth sentence with a period. And the fifth."
sentence_truncate(text, 4).should == "I am a sentence about radio station 95.5 WHOT. What a hot station! I love that one. Don't you?"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment