lig*_*yrs 18 methods console ruby-on-rails
我在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
Run Code Online (Sandbox Code Playgroud)
编辑:哇,1000次观看.我希望这个问题对人们起到了帮助作用.当我回顾这一点时,令我惊讶的是,仅仅一年多以前,我无法弄清楚实例方法和类方法之间的区别.现在我在ruby,Rails和许多其他语言/框架中编写复杂的面向服务的应用程序和后端. Stack Overflow就是这个原因.非常感谢这个社区赋予人们解决问题和理解他们的解决方案的权力.
Rya*_*igg 22
看起来你想要将它用作类方法,所以你必须像这样定义它:
def self.generate_list
...
end
Run Code Online (Sandbox Code Playgroud)
然后你可以称之为Podcast.generate_list.
rai*_*ive 13
从您的代码中,您的generate_list方法看起来实际上构建了Podcast并保存了它?
启动rails控制台:
$ rails console
并创建一个新的Podcast,在其上调用方法:
> pod = Podcast.new
> pod.generate_list
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16773 次 |
| 最近记录: |