nicolaswecandoit nicolaswecandoit - 1 month ago 14
Ruby Question

Split youtube url rails

I m trying to parse youtube url. At this time my code is ok with standard youtube url.

https://www.youtube.com/watch?v=tYMFIIVOHyo


But don't work with list or youtu.be like this

https://www.youtube.com/watch?v=tYMFIIVOHyo&list=UUH3V-b6weBfTrDuyJgFioOw
https://youtu.be/tYMFIIVOHyo?list=UUH3V-b6weBfTrDuyJgFioOw
https://youtu.be/tYMFIIVOHyo


My code is

module CampingsHelper
def embed(youtube_url)
youtube_id = youtube_url.split("=").last
content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{youtube_id}")
end


How I can fix this ?

By the way I want to show an alert if url isn't from youtube.

Answer

You can use regular expression:

youtube_id = youtube_url[/(?<=v=)[^&]+|(?<=https:\/\/youtu.be\/)[^&?]+/]

To show an alert can just check that URL doesn't start with https://www.youtube.com, https://youtube.com or https://youtu.be