Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Last active December 17, 2015 18:09
Show Gist options
  • Save benshimmin/5650829 to your computer and use it in GitHub Desktop.
Save benshimmin/5650829 to your computer and use it in GitHub Desktop.
Truncating Markdown with Redcarpet
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
@Khomyachok5
Copy link

There's one more elegant solution described here:
http://devblog.boonecommunitynetwork.com/rails-and-markdown/

<%= truncate( strip_tags( markdown(post.description) ), length: 50) %>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment