Truncate Markdown?
- Write/find an intelligent HTML truncating function
The following from http://mikeburnscoder.wordpress.com/2006/11/11/truncating-html-in-ruby/, with some modifications will correctly truncate HTML, and easily allow appending a string before the closing tags.
>> puts "<p><b><a href=\"hi\">Something</a></p>".truncate_html(5, at_end = "...")
=> <p><b><a href="hi">Someth...</a></b></p>
The modified code:
require 'rexml/parsers/pullparser'
class String
def truncate_html(len = 30, at_end = nil)
p = REXML::Parsers::PullParser.new(self)
tags = []
new_len = len
results = ''
while p.has_next? && new_len > 0
p_e = p.pull
case p_e.event_type
when :start_element
tags.push p_e[0]
results << "<#{tags.last}#{attrs_to_s(p_e[1])}>"
when :end_element
results << "</#{tags.pop}>"
when :text
results << p_e[0][0..new_len]
new_len -= p_e[0].length
else
results << "<!-- #{p_e.inspect} -->"
end
end
if at_end
results << "..."
end
tags.reverse.each do |tag|
results << "</#{tag}>"
end
results
end
private
def attrs_to_s(attrs)
if attrs.empty?
''
else
' ' + attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ')
end
end
end
How do i truncate a post (HTML/Markdown) but not give invalid markup
In case of HTML it's been answered before.
In case of Markdown, you could convert whole Markdown text to HTML, and see previous point. Otherwise you'd have to write Markdown parser (state machine) that parses source up to a certain point, keeping track of all open constructs, and then closes all of them.
Is there a markdown friendly alternative to truncatechars:x ?
You can use the truncatechars_html
tag.
{{ post.text | custom_markdown | truncatechars_html:160 }}
Combining truncate with Redcarpet markdown in Rails: Links don't work
That link isn't Markdown though, it's HTML. Maybe change it to Markdown?
<%= markdown(truncate(post.content, length: 600,
separator: ' ', omission: '... ') {
"[read more](#{post_path(post)})"
}) %>
Change post_path
to something appropriate if that's not right.
Related Topics
Ruby Gems Returns "Command Not Found"
Homebrew Installation on MAC Os X Failed to Connect to Raw.Githubusercontent.Com Port 443
How to Easily Parse a Url with Parameters in a Rails Test
How to Set the Socket Timeout in Ruby
Is There a Way in Ruby 1.9 to Remove Invalid Byte Sequences from Strings
Rails - Pass Id Parameter on a Link_To
How to Use Gems Not in a Gemfile When Working with Bundler
How to Skip Has_Secure_Password Validations
Given a Class, See If Instance Has Method (Ruby)
Best Way to Pretty Print a Hash
How to Implement Cookie Support in Ruby Net/Http
How to Remove the String "\N" from Within a Ruby String
To Change Directory Inside a Ruby Script
What Is the Use of Secret_Key_Base in Rails 4
How to Get a Backtrace from a Systemstackerror: Stack Level Too Deep