Last active
December 17, 2015 18:09
-
-
Save benshimmin/5650829 to your computer and use it in GitHub Desktop.
Truncating Markdown with Redcarpet
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
require "redcarpet" | |
require "redcarpet/render_strip" | |
# I'm not suggesting this is particularly sane, but it works. | |
# | |
# The little bit of regex fixes cases where two paragraphs get squished | |
# together and you end up with the unsightly | |
# | |
# "end of sentence.New sentence" | |
# | |
# when you want | |
# | |
# "end of sentence. New sentence" | |
# | |
# (I'm sure there are *loads* of edge-cases it will break on, but | |
# this sort of handles some common cases, including various bits of | |
# punctuation.) | |
def get_content | |
# return some text in Markdown here | |
end | |
def get_truncated_content(len = 40, ellipsis = "...") | |
markdown = Redcarpet::Markdown.new(Redcarpet::Render::StripDown) | |
content = markdown.render(get_content).split " " | |
truncated = content[0...len] | |
truncated.join(" ").gsub(/([a-z])(\.|[\.\?\!]?[\'|\"]|\!|\?)([A-Z])/) { | |
"#{$1}#{$2} #{$3}" | |
} << ( content.size > len ? ellipsis : "" ) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's one more elegant solution described here:
http://devblog.boonecommunitynetwork.com/rails-and-markdown/
<%= truncate( strip_tags( markdown(post.description) ), length: 50) %>