Markdown Image Tags as YouTube and Embed Blocks

Abuse markdown image tags to easily embed YouTube videos and embedded resources in documents

In markdown, an image tag look something like this when you want to drop it into a document.

![alt text](https://example.com/image.jpg)

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:

![YouTube video update of my Phlex on Rails course](https://youtu.be/20TEOGOtXTY)

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.

Screenshot of YouTube embed

See it live in the Phlex on Rails: Week One Update article.

Do you want to learn Phlex 💪 and enjoy these code examples?

Support Beautiful Ruby by pre-ordering the Phlex on Rails video course.

Pre-order the video course for $379 $249