class Youtube

Retrieve channel's video from YouTube

Constants

CHANNEL_ENDPOINT
PLAYLIST_ENDPOINT
YOUTUBE_URL

Public Class Methods

new(api_key) click to toggle source
# File lib/service/youtube.rb, line 8
def initialize(api_key)
  @api_key = api_key
  @agent = Mechanize.new
end

Public Instance Methods

last_content(channel_id) click to toggle source
# File lib/service/youtube.rb, line 28
def last_content(channel_id)
  videos(channel_id).first
end
random_content(channel_id) click to toggle source
# File lib/service/youtube.rb, line 32
def random_content(channel_id)
  videos(channel_id).sample
end
video_from_playlist(playlist_id) click to toggle source
# File lib/service/youtube.rb, line 17
def video_from_playlist(playlist_id)
  params = {
    playlistId: playlist_id,
    key: @api_key,
    part: 'snippet',
    maxResults: 50
  }
  response = parse_response(@agent.get(PLAYLIST_ENDPOINT, params))
  parse_videos(response)
end
videos(channel_id) click to toggle source
# File lib/service/youtube.rb, line 13
def videos(channel_id)
  playlists(channel_id).map { |playlist| video_from_playlist(playlist) }.flatten
end

Private Instance Methods

parse_response(response) click to toggle source
# File lib/service/youtube.rb, line 38
def parse_response(response)
  JSON.parse(response.body)
end
parse_video(video) click to toggle source
# File lib/service/youtube.rb, line 56
def parse_video(video)
  {
    title: video['title'],
    url: "#{YOUTUBE_URL}/#{video['resourceId']['videoId']}"
  }
end
parse_videos(result) click to toggle source
# File lib/service/youtube.rb, line 52
def parse_videos(result)
  result['items'].map { |item| parse_video(item['snippet']) }
end
playlists(channel_id) click to toggle source
# File lib/service/youtube.rb, line 42
def playlists(channel_id)
  params = {
    key: @api_key,
    part: 'contentDetails',
    id: channel_id
  }
  response = parse_response(@agent.get(CHANNEL_ENDPOINT, params))
  response['items'].map { |item| item['contentDetails'].values.first['uploads'] }
end