The simplest solution seems to be the following. I use http://youtube/VMD-z2Xni8U
in my Markdown to embed a YouTube video. I then allow autolinking in Redcarpet to autolink this.
# /lib/helpers/markdown_renderer_with_special_links.rb
class MarkdownRendererWithSpecialLinks < Redcarpet::Render::HTML
def autolink(link, link_type)
case link_type
when :url then url_link(link)
when :email then email_link(link)
end
end
def url_link(link)
case link
when /^http:\/\/youtube/ then youtube_link(link)
else normal_link(link)
end
end
def youtube_link(link)
parameters_start = link.index('?')
video_id = link[15..(parameters_start ? parameters_start-1 : -1)]
"<iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/#{video_id}?rel=0\" frameborder=\"0\" allowfullscreen></iframe>"
end
def normal_link(link)
"<a href=\"#{link}\">#{link}</a>"
end
def email_link(email)
"<a href=\"mailto:#{email}\">#{email}</a>"
end
end
I then create a markdown
method to use in any view or controller when displaying markdown content:
# /app/helpers/application_helper.rb
module ApplicationHelper
require './lib/helpers/markdown_renderer_with_special_links'
def markdown(content)
@markdown ||= Redcarpet::Markdown.new(MarkdownRendererWithSpecialLinks, autolink: true, space_after_headers: true, fenced_code_blocks: true)
@markdown.render(content).html_safe
end
end