Skip to content

Instantly share code, notes, and snippets.

@niquepa
Last active January 25, 2023 23:51
Show Gist options
  • Save niquepa/4c59b7d52a15dde2367a to your computer and use it in GitHub Desktop.
Save niquepa/4c59b7d52a15dde2367a to your computer and use it in GitHub Desktop.
Ruby rails extract youtube ID from URL
def youtube_id(youtube_url)
regex = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
match = regex.match(youtube_url)
if match && !match[1].blank?
match[1]
else
nil
end
end
def video_embed(video_url)
# REGEX PARA EXTRAER EL ID DEL VIDEO
regex_id = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/|vimeo\.com\/)([a-zA-Z0-9_-]{8,11})/
match_id = regex_id.match(video_url)
video_id = ""
if match_id && !match_id[1].blank?
video_id = match_id[1]
end
# REGEX PARA EXTRAER EL PROVEEDOR - YOUTUBE/VIMEO
regex_prov = /(youtube|youtu\.be|vimeo)/
match_prov = regex_prov.match(video_url)
video_prov = ""
if match_prov && !match_prov[1].blank?
video_prov = case match_prov[1]
when "youtube"
:youtube
when "youtu.be"
:youtube
when "vimeo"
:vimeo
end
end
case video_prov
when :youtube
"https://www.youtube.com/embed/#{video_id}"
when :vimeo
"https://player.vimeo.com/video/#{video_id}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment