RailsのModel内でYoutube動画を検索する
タイトル通り、RailsのModel内でYoutube動画を検索してみました。
RubyでYouyube動画を検索する方法はネットで調べれば
直ぐに分かりますが、備忘録として載せておきます。
今回は以下のサイトを参考にしました。(てか、ほとんど真似ている・・・)
RubyプログラムからYouTube Data APIを使って動画検索 : 兀兀 -プログラミング編-
以下、手順です。Railsのプロジェクトは作成済みとします。
1.Gemfileに以下を記述し、bundle install。
gem 'nokogiri'
2.Youtubeから検索するためのVideoモデルと、RSpecのvideo_specを作成する。
3.videoモデルにsearch()メソッドを追加し、上記サイトのサンプルソースを貼り付け、実行すると以下のエラー。
dynamic constant assignment
原因は"URL"が大文字であるため、定数として認識されるため。
"URL"をメソッドの外に出す。
4.ここまででYoutubeから検索はできるが、今回の要件に合わせて次の変更を加えた。
・検索キーワードは引数で渡されるようにする。
・検索したYoutube動画のタイトルと、動画のID?をArticleモデルに入れて返すようにした。
以上です。参考までに作ったソースを載せておきます。
video.rb
require 'nokogiri'
require 'open-uri'class Video < ActiveRecord::Base
URL = 'http://gdata.youtube.com/feeds/api/videos?vq='def self.search(keyword)
keywords = URI.encode(keyword)
options = '&orderby=published'uri = URI(URL + keywords + options)
articles = []
doc.search('entry').each do |entry|
article = Article.new
article.title = entry.search('title').text
article.youtube_video = entry.xpath('media:group/media:player').first['url'].scan(/\bv=\w*/)[0].delete('v=')
articles.push(article)
endreturn articles
end
end
video_spec.rb
require 'spec_helper'describe Video do
describe "search" do
it "youtubeから検索すること" do
articles = Video.search('Top Gear - BBC')
expect(articles.count).to be > 0
expect(articles[0].title).should_not eq("")
expect(articles[0].youtube_video).should_not eq("")
end
end
end