使用 Nokogiri 将文档片段包装在 div

Use Nokogiri to wrap a document fragment in a div

我正在尝试使用 Nokogiri 查找 iframe 并将其包装在 div 中,并带有特定的 class。

到目前为止,我有以下代码,但这会向 iframe 添加一个视频容器 class。我需要将 iframe 包装在 div 中,并给 div 视频容器 class:

def clean_html
  frag = Nokogiri::HTML::DocumentFragment.parse(self.description)
  embeds = frag.css("iframe")
  embeds.add_class("video-container") if embeds.count > 0
  self.description = frag.to_html
end
def clean_html
  frag = Nokogiri::HTML::DocumentFragment.parse(self.description)
  embeds = frag.css("iframe")
  embeds.wrap("<div class='video-container'>") if embeds.count > 0
  self.description = frag.to_html
end

没有意识到有一个包装功能可以让您用一些 html...face palm

包装片段