Reputation: 199
How can I use youtube_it gem for Ruby on Rails to get videos from youtube channel (https://www.youtube.com/channel/UCwHnsUEYrQUTUxC4dvrv0QQ)?
Or can you advise me an another gem that can help me?
Upvotes: 4
Views: 786
Reputation: 4231
this is how I do it.
I have this in my config/initializers/youtube_it.rb:
$youtube_it = YouTubeIt::Client.new(dev_key: ENV['YOUTUBE_KEY'])
Get the first page of videos:
query = {
author: channel_url.split('/').last,
order_by: 'published',
page: 1,
}
# scraping from newesr to oldest
videos = $youtube_it.videos_by(query).videos
And here is a scraping example, where you'd schedule a job to call the scrape method periodically.
The method first scrapes from newest videos to oldest. Then the backward_scrape_done
is set to true
and then scrapes only new videos.
class Import < ActiveRecord::Base
def scrape
query = {
author: channel_url.split('/').last,
order_by: 'published',
}
query[:page] = cursor
# scraping from newesr to oldest
videos = fetch_videos(query)
if videos.count == 0
# we've reached the end
self.backward_scrape_done = true
self.cursor = 0
end
for video in videos
add_video video
end
# next time scrape next page
self.cursor = cursor + 1
ensure
self.scraped_at = Time.now
self.save!
end
def fetch_videos(query)
$youtube_it.videos_by(query).videos
end
def add_video video
url = video.player_url.
gsub(/[?&]feature=youtube_gdata_player/, '')
# skip this video if its already there
if Video.where(youtube_url: url).first
self.cursor = 0
save
return
end
video = YoutubeVideo.create!(
title: video.title,
duration: video.duration,
description: video.description,
youtube_url: url,
)
end
end
Hope that helps!
Update: As youtube is getting rid of its API V2 soon, you should switch to something that supports the latest API, like the yt
gem I use now:
https://github.com/Fullscreen/yt
Upvotes: 1