Skip to content

Instantly share code, notes, and snippets.

@alexdunae
Created September 30, 2011 19:07
Show Gist options
  • Save alexdunae/1254685 to your computer and use it in GitHub Desktop.
Save alexdunae/1254685 to your computer and use it in GitHub Desktop.
Parse embed video URL snippet
test 'getting embed data for youtube urls' do
result = {:youtube => 'dQw4w9WgXcQ'}
['http://youtu.be/dQw4w9WgXcQ',
'http://www.youtube.com/embed/dQw4w9WgXcQ',
'http://www.youtube.com/watch?v=dQw4w9WgXcQ',
'https://www.YOUTUBE.com/?v=dQw4w9WgXcQ',
'http://www.youtube.com/v/dQw4w9WgXcQ',
'http://www.youtube.com/e/dQw4w9WgXcQ',
'http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ',
'http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ',
'http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ',
'http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ'].each do |url|
m = Media.new({:url => url})
assert_equal result, m.embed_data
end
end
test 'getting embed data for vimeo urls' do
{'http://vimeo.com/staffpicks#17769804' => '17769804',
'http://vimeo.com/#/featured/19403316' => '19403316',
'http://vimeo.com/channels/gnarchive#29824247' => '29824247',
'https://vimeo.com/hd#28628704' => '28628704',
'http://vimeo.com/couchmode/channels/hd/sort:newest/28628704' => '28628704',
'http://VIMEO.COM/25108697' => '25108697',
'http://www.vimeo.com/25108697' => '25108697'
}.each do |url, result|
m = Media.new({:url => url})
assert_equal({:vimeo => result}, m.embed_data)
end
end
test 'getting embed data for unknown urls' do
url = 'http://example.com/1234'
m = Media.new({:url => url})
assert_equal({:other => url}, m.embed_data)
end
# seemed like a good idea until I remembered OEmbed
# stored in case this is needed later
# from http://stackoverflow.com/questions/2936467/parse-youtube-video-id-using-preg-match/6382259#6382259
YOUTUBE_RX = Regexp.new('(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})', true)
VIMEO_RX = Regexp.new('vimeo\.com/(.*[/#])*([0-9]+)\Z', true)
# parse the media's URL and attempt to return a hash with the
# type and the embed ID
#
# currently supports YouTube and Vimeo
#
# return values:
# nil
# {:youtube => 'video_id'}
# {:vimeo => 'video_id'}
# {:other => 'url' }
def embed_data
return nil if url.blank?
begin
if m = YOUTUBE_RX.match(url)
data = {:youtube => m[1]}
elsif m = VIMEO_RX.match(url)
data = {:vimeo => m[2]}
end
rescue; end
data || {:other => url}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment