Module: YoutubeSearch

Defined in:
lib/youtube_search.rb,
lib/youtube_search/version.rb

Constant Summary collapse

API_URL =
'http://gdata.youtube.com/feeds/api'
VERSION =
'0.2.0'

Class Method Summary collapse

Class Method Details

.parse(xml, options = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/youtube_search.rb', line 39

def parse(xml, options={})
  key = options[:key] || 'feed/entry'

  elements_in(xml, key).map do |element|
    entry = xml_to_hash(element)
    entry['video_id'] = if options[:type] == :playlist
      element.elements['*/yt:videoid'].text
    else
      entry['id'].split('/').last
    end

    duration = element.elements['*/yt:duration']
    entry['duration'] = duration.attributes['seconds'] if duration

    no_embed = element.elements['yt:noembed'] || element.elements['yt:private']
    entry['embeddable'] = !(no_embed)

    entry['raw'] = element

    entry
  end
end

.playlist_videos(playlist_id, options = {}) ⇒ Object



24
25
26
27
# File 'lib/youtube_search.rb', line 24

def playlist_videos(playlist_id, options={})
  playlist_id = playlist_id.sub(/^PL/, "")
  videos "#{API_URL}/playlists/#{playlist_id}?v=2", options[:format]
end

.search(query, options = {}) ⇒ Object



16
17
18
# File 'lib/youtube_search.rb', line 16

def search(query, options={})
  search_page("#{API_URL}/videos", query, options)
end

.search_page(page, query, options = {}) ⇒ Object



9
10
11
12
13
14
# File 'lib/youtube_search.rb', line 9

def search_page(page, query, options={})
  options = options_with_per_page_and_page(options)
  query = options.merge(:q => query).map{|k,v| "#{CGI.escape k.to_s}=#{CGI.escape v.to_s}" }.join('&')
  xml = open("#{page}?#{query}").read
  parse(xml)
end

.search_playlists(query, options = {}) ⇒ Object



20
21
22
# File 'lib/youtube_search.rb', line 20

def search_playlists(query, options={})
  search_page("#{API_URL}/playlists/snippets", query, options.merge(:v => 2))
end

.single(video_id, options = {}) ⇒ Object



34
35
36
37
# File 'lib/youtube_search.rb', line 34

def single(video_id, options={})
  options = options.merge(:key => 'entry')
  videos "#{API_URL}/videos/#{video_id}", :xml, options
end

.user_channel_videos(channel_id, options = {}) ⇒ Object



29
30
31
32
# File 'lib/youtube_search.rb', line 29

def user_channel_videos(channel_id, options={})
  channel_id = channel_id.sub(/^UC/, "")
  videos "#{API_URL}/users/#{channel_id}/uploads?v=2", options[:format]
end