Edit images info in html text fields / images not showing nicely in html fields

I usually end up parsing all HTML content and rewriting img tags to support responsive sizing. Here are a couple of pieces of code I wrote for Middleman that may be a starting point to others looking to do something similar.

Responsive Image Sizing Partial

This partial takes an Imgix image URL such as one from a Dato model, and spits out a responsive image. I needed it for 100vw images, if your image sizing is more complex you’d need to adjust that.

<%
raise "Image full requires a source URL `src`" unless defined?(src)
raise "Image full requires an image description `alt`" unless defined?(alt)
raise "Image full doesn’t accept source URLs with a querystring" if src.include?("?")
%>

<picture>
  <%= image_tag "#{src}?w=1000&auto=format&q=50", {
    alt: alt,
    class: "image-full",
    loading: "lazy",
    sizes: "100vw",
    srcset: (300..4500).step(300).map { |size| "#{src}?w=#{size}&auto=format&q=25 #{size}w" }.join(", ")
  } %>
</picture>

HTML Parsing Helper

This helper reads in markup from a Dato model, parses it with Nokogiri, and rewrites links as needed for the format my editors were using at the time. You could adapt this to walk the document for img tags and replace them with the partial above, or transform them some other way.

def article_body_html(article)
  ids = dato.articles.map(&:id)
  html = Kramdown::Document.new(article.body, { header_offset: 1 }).to_html
  document = Nokogiri::HTML::DocumentFragment.parse(html)

  document.css("a").each do |anchor|
    id = anchor.attribute("href").value

    if ids.include?(id)
      article = dato.find(id)

      if article
        anchor.attribute("href").value = article_path(article)
      end
    end
  end

  document.to_html
end