You can mutate the resulting HTML code using Nokogiri , this is almost all the code needed for your task.
def responsive_img_src(html_source) doc = Nokogiri::HTML::Document.parse('<html></html>', nil, 'UTF-8') fragment = Nokogiri::HTML::DocumentFragment.new(doc, html_source) fragment.css('img').each { |img| img['data-src'] = img['src'] } return fragment.to_html end
You cannot directly use Nokogiri::HTML(html_source) to parse your source, as it will transfer the output to a well-formed HTML document. This is why you need a DocumentFragment.
source share