Created
April 9, 2015 11:23
-
-
Save attilahorvath/e829ff95bad9220c6e8e to your computer and use it in GitHub Desktop.
Extract video ID and get cover image URL from a YouTube embed code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Method to get the cover image URL for a YouTube video by its ID | |
# There are several cover images avaiable for every video, you can specify which one you need through the type parameter | |
# For a list of possible cover types see http://stackoverflow.com/a/2068371/3463845 | |
# The returned URL will be protocol-relative, so it should work on sides loaded through HTTP and HTTPS as well | |
def youtube_cover_for(id, type = :default) | |
"//img.youtube.com/vi/#{id}/#{type}.jpg" | |
end | |
# Method to extract the video ID from a YouTube embed code | |
# This very simple regex works by exploiting the fact that the YouTube video IDs are always 11 characters long | |
def extract_youtube_id_from(embed_code) | |
embed_code.match(/embed\/(.{11})/)[1] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment