I've written a ruby youtube url parser. It's designed to take an input of a youtube url of one of the following structures (these are currently the youtube url structures that I could find, maybe there's more?):
http://youtu.be/sGE4HMvDe-Q
http://www.youtube.com/watch?v=Lp7E973zozc&feature=relmfu
http://www.youtube.com/p/A0C3C1D163BE880A?hl=en_US&fs=1
The aim is to save just the id of the clip or playlist so that it can be embedded, so if it's a clip: 'sGE4HMvDe-Q'
, or if it's a playlist: 'p/A0C3C1D163BE880A'
The parser I wrote works fine for these urls, but seems a bit brittle and long-winded, I'm just wondering if someone could suggest a nicer ruby approach to this problem?
def parse_youtube
a = url.split('//').last.split('/')
b = a.last.split('watch?v=').last.split('?').first.split('&').first
if a[1] == 'p'
url = "p/#{b}"
else
url = b
end
end
Using the Addressable gem, you can save yourself some work. There's also a URI module in stdlib, but Addressable is more powerful.
EDIT | Removed madness. Didn't notice Addressable provides
#query_values
already.Depending on how you use this, you might want a better validation that the URL is indeed from youtube.
UPDATE:
Coming back to this a few years later. I've always been annoyed by how sloppy the original answer was. Since the validity of the Youtube domain wasn't validated anyway, I've removed some of the slop.