Question

I'm working with Nokogiri and I'm a newbye. I'm parsing an HTML document to match some placeholder, and after match I must replace the widget placeholder with some generated HTML.

I create this method:

doc = Nokogiri::HTML.fragment(raw)
matches = doc.xpath(".//widget")
if matches.present?
  matches.each do |match|
    media_replace(..)
else
  self.body = raw
end

I have some matches, and every match has this attributes.

 matches.first.attributes
{"data_id"=>#(Attr:0x3fdd42e2cebc { name = "data_id", value = "5" }),
"data_type"=>#(Attr:0x3fdd42e2ce94 { name = "data_type", value = "gallery" })}

How can I extract these attributes(gallery and 5) to pass them to my media_replace method? Media_replace method return to me an 'html': how can I replace every 'match' with the returned HTML?

Was it helpful?

Solution

To get attribute values from a node you can use the [] method. For example:

media_replace(match['data_id'], match['data_gallery'])

To replace the node, use the replace or swap methods (assuming media_replace returns a string or other compatible object):

new_html = media_replace(...)
match.replace(new_html)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top