How to embed YouTube video in rails app dynamically

So, I have a rails app that allows users to post links to youtube and rate songs / links with the thumb.

However, users must physically copy and paste the link into the browser to listen to the song. For a better UX, I would like the YouTube links provided to be embedded in the app as a video. So how can this be done dynamically?

In other words, you can send the YouTube link, it will be saved, for example. song_id (1). You can click song_id (1), and instead of just seeing the link, you will also see the embedded video on YouTube.

Updated show.html.erb:

<%- model_class = Song -%> <div class="page-header"> <h1><%=t '.title', :default => model_class.model_name.human.titleize %></h1> </div> <dl class="dl-horizontal"> <dt><strong><%= model_class.human_attribute_name(:title) %>:</strong></dt> <dd><%= @song.title %></dd> <dt><strong><%= model_class.human_attribute_name(:url) %>:</strong></dt> <dd><%= YouTubeAddy.extract_video_id(@song.url) %> </dd> <iframe width="#{width}" height="#{height}" src="http://www.youtube.com/embed/#{youtube_id}" frameborder="0"></iframe> 

songhelper.rb

 module SongsHelper def youtube_id YouTubeAddy.extract_video_id(@song.url) end end 
+4
source share
2 answers

You could

  • Extract the youtube video id from the link provided.

    for example, someone sends this link http://www.youtube.com/watch?v=XwmtNk_Yb2Q

    you need XwmtNk_Yb2Q

  • With this id, you can display the iframe element that includes the video.

    <iframe width="#{width}" height="#{height}" src="http://www.youtube.com/embed/#{video_id}" frameborder="0"></iframe>

here's how @Elie Gnrd's proposed stone does it .

+3
source

I developed the gist and converted it to the correct Ruby class, which supports the generation of URLs for insertion and / or the generation of iframes for youtube as well as vimeo .

Using
 url = 'https://youtu.be/OaDhY_y8WTo' generator = VideoEmbedUrlGenerator.new(url) generator.construct_url #=> "https://www.youtube.com/embed/OaDhY_y8WTo" generator.construct_iframe #=> "<iframe width=\"640\" height=\"480\" frameborder=\"0\" allow=\"autoplay; fullscreen\" allowfullscreen, src='https://www.youtube.com/embed/OaDhY_y8WTo'></iframe>" 

The implementation can be found here: gist

0
source

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


All Articles