add support to keep img tags when converting to html

This commit is contained in:
Régis Hanol 2017-04-28 22:14:46 +02:00
parent 51ee49aad2
commit aba76bace6
3 changed files with 16 additions and 5 deletions

View File

@ -194,7 +194,7 @@ module Email
end
markdown, elided_markdown = if html.present?
markdown = HtmlToMarkdown.new(html).to_markdown
markdown = HtmlToMarkdown.new(html, keep_img_tags: true).to_markdown
markdown = trim_discourse_markers(markdown)
EmailReplyTrimmer.trim(markdown, true)
end

View File

@ -6,7 +6,8 @@ class HtmlToMarkdown
def initialize(name, head="", body="", opened=false, markdown=""); super; end
end
def initialize(html)
def initialize(html, opts={})
@opts = opts || {}
@doc = Nokogiri::HTML(html)
remove_whitespaces!
end
@ -133,8 +134,12 @@ class HtmlToMarkdown
end
def visit_img(node)
title = node["alt"].presence || node["title"].presence
@stack[-1].markdown << "![#{title}](#{node["src"]})"
if @opts[:keep_img_tags]
@stack[-1].markdown << node.to_html
else
title = node["alt"].presence || node["title"].presence
@stack[-1].markdown << "![#{title}](#{node["src"]})"
end
end
def visit_a(node)

View File

@ -31,8 +31,14 @@ describe HtmlToMarkdown do
expect(html_to_markdown(%Q{<a href="https://www.discourse.org">Discourse</a>})).to eq("[Discourse](https://www.discourse.org)")
end
HTML_WITH_IMG ||= %Q{<img src="https://www.discourse.org/logo.svg" alt="Discourse Logo">}
it "converts <img>" do
expect(html_to_markdown(%Q{<img src="https://www.discourse.org/logo.svg" alt="Discourse Logo">})).to eq("![Discourse Logo](https://www.discourse.org/logo.svg)")
expect(html_to_markdown(HTML_WITH_IMG)).to eq("![Discourse Logo](https://www.discourse.org/logo.svg)")
end
it "keeps <img> with 'keep_img_tags'" do
expect(HtmlToMarkdown.new(HTML_WITH_IMG, keep_img_tags: true).to_markdown).to eq(HTML_WITH_IMG)
end
(1..6).each do |n|