Converting a regular Youtube 'link' into an embedded video
I do this quite often for clients, the gist of it is that you parse out the ID from the URL, then generate the iframe
HTML using this.
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" width="640" height="390" src="http://www.youtube.com/embed/#{ youtube_id }" frameborder="0" allowfullscreen></iframe>}
end
youtube_embed('youtu.be/jJrzIdDUfT4')
# => <iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/jJrzIdDUfT4" frameborder="0" allowfullscreen></iframe>
I put this in a helper. Change the height, width and options to taste.
Another answer is to use this gem which handles youtube and vimeo, and could be expanded to more. It also integrates well with AR so you can cache the resulting html instead of filtering on each render:
https://github.com/dejan/auto_html
I used the highest rated answer about with the function youtube_embed but when I implemented in my view I was seeing the iframe code appear in my page, but no video. I added raw before the function call and all is good with the page now.
Inside my view.html.erb
<p><%= raw(youtube_embed(@experiment.researchsection.videolink)) %></p>