In markdown, image tags look something like this:

For my projects, I don’t think of these tags strictly as images, but rather blocks of content with an image representation. In practice, that means I want to embed YouTube vidoes in my content pages like this:

Out of the box this wouldn’t work, but fortunately since I use the Markdown Rails gem, I can intercept image tags and process them as blocks of content. Here’s what my Markdown parser looks like in my application.
class ApplicationMarkdown < MarkdownRails::Renderer::Rails
# Process markdown image blocks
def image(link, title, alt)
url = URI(link)
case url.host
when "youtu.be"
youtube_tag url, alt
else
super
end
end
# ...
private
# This is provided as an example; there's many more YouTube URLs that this wouldn't catch.
def youtube_tag(url, alt)
<<~HTML
<iframe
class="aspect-video w-full rounded"
src="https://www.youtube-nocookie.com/embed#{url.path}"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen
></iframe>
HTML
end
end
When I stack it all up and publish the content, I see a YouTube embed.
See it live in the Phlex on Rails: Week One Update article.