Created
June 3, 2010 20:40
-
-
Save coryschires/424449 to your computer and use it in GitHub Desktop.
sentence_truncate helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on http://stackoverflow.com/questions/1293573/rails-smart-text-truncation | |
def sentence_truncate(string, num_sentences) | |
string = scrub_html(string) | |
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 | |
# force max length in case of really long sentences | |
truncated_sentence = truncate(truncated_sentence, :length => 350) if truncated_sentence.length > 350 | |
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