Last active
October 19, 2016 21:13
-
-
Save cyzanfar/82a46596b5fa4e76fd04732f2df852d0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'google/api_client' | |
module Youtube | |
class VideoList | |
YOUTUBE_API_SERVICE_NAME = 'youtube' | |
YOUTUBE_API_VERSION = 'v3' | |
YOUTUBE_ID_REGEX = /^(https?:\/\/(?:youtu.be\/|www.youtube.com\/(?:watch\?v=|embed\/))(?<youtube_id>[\w\-]{4,16})\??([\w\-\=]+)?)$/ | |
attr_accessor :video_id, :description, :title, :url | |
def initialize(video_url) | |
@url = video_url | |
extract_youtube_id | |
set_youtube_data | |
end | |
def client | |
Google::APIClient.new( | |
key: settings.api_key, | |
authorization: nil, | |
application_name: settings.application_name | |
) | |
end | |
def youtube | |
client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION ) | |
end | |
def search_response | |
client.execute!( | |
api_method: youtube.search.list, | |
parameters: { | |
part: 'snippet', | |
q: video_id | |
} | |
) | |
end | |
def set_youtube_data | |
data = search_response.data.items.first | |
return if data.blank? | |
@description = data["description"] | |
@title = data["title"] | |
end | |
private | |
def settings | |
Figleaf::Settings.youtube | |
end | |
def extract_youtube_id | |
@url.match(YOUTUBE_ID_REGEX) do |m| | |
self.video_id = m[:youtube_id] | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment