How to embed YouTube videos in Markdown with Redcarpet for Rails?

I use the Redcarpet Markdown parser in Rails 4.1 so that employees can write messages to each other with some formatting. I want them to be able to embed a YouTube video. Maybe something like:

Hey, *check out* my video: [VMD-z2Xni8U](youtube)

This will lead to the conclusion:

Hey check out my video:<iframe width="560" height="315" src="//www.youtube.com/embed/VMD-z2Xni8U" frameborder="0" allowfullscreen></iframe>

Is there a way to do this in the Redcarpet Markdown parser? I guess I have to write my own custom parser? What is a suitable way to do this if there is a way? Is Markdown's standard way to do this possible?

+4
source share
1

, , . http://youtube/VMD-z2Xni8U Markdown YouTube. Redcarpet .

# /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

markdown :

# /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
+7

Source: https://habr.com/ru/post/1536379/


All Articles