Reputation: 2753
If user types youtube url in body and save record, I'd like to show its thumbnail in view.
Is there any good techniques? or good gem for that?
sample typed in url:
http://www.youtube.com/watch?v=qrO4YZeyl0I
Upvotes: 2
Views: 2335
Reputation: 3702
I needed youtube thumbnails recently, so just an update. Currently urls look like:
http://i1.ytimg.com/vi/video_id/default.jpg
http://i1.ytimg.com/vi/video_id/mqdefault.jpg
http://i1.ytimg.com/vi/video_id/hqdefault.jpg
http://i1.ytimg.com/vi/video_id/sddefault.jpg
http://i1.ytimg.com/vi/video_id/1.jpg
http://i1.ytimg.com/vi/video_id/2.jpg
http://i1.ytimg.com/vi/video_id/3.jpg
Upvotes: 4
Reputation: 2488
Are you parsing the video ID code from the URL? I.e. in your example it'd be qrO4YZeyl0I
.
Once you have this you can do anything you want with it. There are four thumbnails generated for each video.
http://img.youtube.com/vi/qrO4YZeyl0I/0.jpg
http://img.youtube.com/vi/qrO4YZeyl0I/1.jpg
http://img.youtube.com/vi/qrO4YZeyl0I/2.jpg
http://img.youtube.com/vi/qrO4YZeyl0I/3.jpg
To simply select the default thumbnail for the video use:
http://img.youtube.com/vi/qrO4YZeyl0I/default.jpg
See this answer for more detail - How do I get a YouTube video thumbnail from the YouTube API?
Upvotes: 8
Reputation: 3470
You can parse the url, and get the thumbnail from the youtube before saving the model:
Gemfile:
gem 'youtube_it'
Model:
before_save :get_youtube_thumbnail
def get_youtube_thumbnail
url = extract_url_from_body
unless url.blank?
client = YouTubeIt::Client.new
response = client.video_by(url)
self.thumbnail = response.thumbnails.first.url
end
end
def extract_url_from_body
URI.extract(body).first
end
View:
<%= image_tag model.thumbnail, alt: model.title %>
Upvotes: 3