Chet
Chet

Reputation: 144

How to edit all image src attributes from a file using nokogiri?

This is what I have right now. Im trying to replace all of the "./" in all my src attributes with "/data/content/.." . Now im able do individually get the attributes and change it. but how can I edit the entire object itself and save it? as im using it as a string object in the view.

@page = Nokogiri::HTML(@html_content_from_uploaded_rar_index_html)
@page.css('img').each do |node|
 node.each do |attr_name,attr_val|
  attr_val.to_s.gsub("./", "/data/content/")
  // need to save page object with updated src attribute values now
 end
end

Thanks

Upvotes: 1

Views: 633

Answers (1)

Anthony L
Anthony L

Reputation: 2169

Something like this should do the trick

page.css('img').each do |node|
 node.each do |attr_name,attr_val|
  node.attributes["src"].value = attr_val.to_s.gsub("./", "/data/content/")
 end
end

You can then retrieve the updated HTML in the usual way.

Upvotes: 4

Related Questions