Skip to content

Instantly share code, notes, and snippets.

@dpsk
Created November 27, 2019 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpsk/c61bed37ce7c7b46eed90ca7fe06862e to your computer and use it in GitHub Desktop.
Save dpsk/c61bed37ce7c7b46eed90ca7fe06862e to your computer and use it in GitHub Desktop.
Small lib for extracting provider and video id from url
class VideoUrl
YOUTUBE_FORMATS = [
%r(https?://youtu\.be/(.+)),
%r(https?://www\.youtube\.com/watch\?v=(.*?)(&|#|$)),
%r(https?://www\.youtube\.com/embed/(.*?)(\?|$)),
%r(https?://www\.youtube\.com/v/(.*?)(#|\?|$)),
%r(https?://www\.youtube\.com/user/.*?#\w/\w/\w/\w/(.+)\b)
]
VIMEO_FORMATS = [
%r(https?://vimeo.com\/(\d+)),
%r(https?:\/\/(www\.)?vimeo.com\/(\d+))
]
attr_accessor :url, :id, :provider
def initialize(url)
@url = url.strip
@provider, @id = parse_video_url
end
def parse_video_url
if url.include? "youtu"
YOUTUBE_FORMATS.find { |format| url =~ format } and $1
["youtube", $1]
elsif url.include? "vimeo"
VIMEO_FORMATS.find { |format| url =~ format } and $1
["vimeo", $1]
else
[]
end
end
end%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment