Rails 3 モデルに、nokogiri を使用して XML を解析するメソッドがあります。このメソッドをコンソールで呼び出してテストするにはどうすればよいでしょうか。
クラス全体は次のとおりです (generate_list を呼び出そうとしています)。
class Podcast < ActiveRecord::Base
validates_uniqueness_of :name
serialize :hosts
def generate_list
# fetch the top 300 podcasts from itunes
itunes_top_300 = Nokogiri.HTML(open("http://itunes.apple.com/us/rss/toppodcasts/limit=300/explicit=true/xml"))
# parse the returned xml
itunes_top_300.xpath('//feed/entry').map do |entry|
new_name = entry.xpath("./name").text
podcast = Podcast.find(:all, :conditions => {:name => new_name})
if podcast.nil?
podcast = Podcast.new(
:name => entry.xpath("./name").text,
:itunesurl => entry.xpath("./link/@href").text,
:category => entry.xpath("./category/@term").text,
:hosts => entry.xpath("./artist").text,
:description => entry.xpath("./summary").text,
:artwork => entry.xpath("./image[@height='170']").text
)
podcast.save
else
podcast.destroy
end
end
end
end
編集: すごい、1000 回も閲覧されました。この質問が私と同じくらい皆さんの役に立てば幸いです。振り返ってみると、1 年ちょっと前まではインスタンス メソッドとクラス メソッドの違いがわからなかったのが驚きです。今では、Ruby、Rails、その他多くの言語/フレームワークで複雑なサービス指向のアプリケーションとバックエンドを作成しています。その理由は Stack Overflow です。人々が問題を解決し、解決策を理解できるようにしてくれたこのコミュニティに心から感謝します。
ベストアンサー1
これをクラスメソッドとして使用したいようですので、次のように定義する必要があります。
def self.generate_list
...
end
これを と呼ぶことができますPodcast.generate_list
。