在Rails中创建HTML段落的文本摘录



我试图为一篇文章提取摘录(markdown解析为HTML(,其中只包含段落中的纯文本。所有HTML都需要被剥离,换行符、制表符和连续的空格都需要用一个空格代替。

我的第一步是创建一个简单的测试:

describe "#from_html" do
it "creates an excerpt from given HTML" do
html = "<p>The spice extends <b>life</b>.<br>The spice    expands consciousness.</p>n
<ul><li>Skip me</li></ul>n
<p>The <i>spice</i> is vital to space travel.</p>"
text = "The spice extends life. The spice expands consciousness. The spice is vital to space travel."
expect(R::ExcerptHelper.from_html(html)).to eq(text)
end
end

然后开始摆弄,想出了这个:

def from_html(html)
Nokogiri::HTML.parse(html).css("p").map{|node|
node.children.map{|child|
child.name == "br" ? child.replace(" ") : child
} << " "
}.join.strip.gsub(/s+/, " ")
end

我在Rails上有点粗鲁,这可能可以做得更高效、更优雅。我希望能在这里找到一些建议。

提前感谢!


进近2

转向消毒方法(感谢@max(,并编写了一个基于Rails::Html::PermitScrubber的自定义洗涤器


进近3

意识到我的源文档的格式是Markdown,我大胆探索了一个自定义的红地毯渲染器。

请参阅我的答案以获取完整的示例。

我最终编写了一个自定义的红地毯渲染器(灵感来自Redcarpet::Render::StripDown(。这似乎是最干净的方法,在格式之间解析和转换最少。

module R::Markdown
class ExcerptRenderer < Redcarpet::Render::Base
# Methods where the first argument is the text content
[
# block-level calls
:paragraph,
# span-level calls
:codespan, :double_emphasis,
:emphasis, :underline, :raw_html,
:triple_emphasis, :strikethrough,
:superscript, :highlight, :quote,
# footnotes
:footnotes, :footnote_def, :footnote_ref,
# low level rendering
:entity, :normal_text
].each do |method|
define_method method do |*args|
args.first
end
end
# Methods where content is replaced with an empty space
[
:autolink, :block_html
].each do |method|
define_method method do |*|
" "
end
end
# Methods we are going to [snip]
[
:list, :image, :table, :block_code
].each do |method|
define_method method do |*|
" [#{method}] "
end
end
# Other methods
def link(link, title, content)
content
end
def header(text, header_level)
" #{text} "
end
def block_quote(quote)
" “#{quote}” "
end
# Replace all whitespace with single space
def postprocess(document)
document.gsub(/s+/, " ").strip
end
end
end

并解析它:

extensions = {
autolink:                     true,
disable_indented_code_blocks: true,
fenced_code_blocks:           true,
lax_spacing:                  true,
no_intra_emphasis:            true,
strikethrough:                true,
superscript:                  true,
tables:                       true
}
markdown = Redcarpet::Markdown.new(R::Markdown::ExcerptRenderer, extensions)
markdown.render(md).html_safe

最新更新