0

Could someone break it out what ruby is doing in here?

I would like to understand the code so I could adapt it in the future. One of the things I wanted to do was to adapt it to Vimeo, but I need to understand what is going on so I can learn more.

module ApplicationHelper
    def youtube_embed(youtube_url)
    if youtube_url[/youtu\.be\/([^\?]*)/]
      youtube_id = $1
    else
      # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367
      youtube_url[/^.*((v\/)|(embed\/)|(watch\?))\??v?=?([^\&\?]*).*/]
      youtube_id = $5
    end

    %Q{<iframe title="YouTube video player" src="https://www.youtube.com/embed/#{ youtube_id }?rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>}
  end
end
Allan
  • 336
  • 3
  • 18

1 Answers1

0

This piece of code tries to build code for embet youtube player from any youtube link on video. This if youtube_url[/youtu\.be\/([^\?]*)/] verifies if given url has a "youtu.be/...." format and then extracts video id. ($1 contains result of evaluating regular expression (expression between /.../) )

If string do not starts with 'youtu.be', code uses some tricky regular expression (which explanation ypu could find if follow link to stackoverflow in code) and then from $5 also gets video id.

And then it returns a string that is the html-code of embed youtube player for that video. It inserts video id at the end of this string using #{youtube_id}

Ngoral
  • 4,215
  • 2
  • 20
  • 37