2

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
MKK
  • 2,713
  • 5
  • 31
  • 51

3 Answers3

8

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?

Community
  • 1
  • 1
John H
  • 2,488
  • 1
  • 21
  • 35
4

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
santuxus
  • 3,662
  • 1
  • 29
  • 35
3

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 %>
subosito
  • 3,420
  • 2
  • 24
  • 12