Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call rails 3 model method in the console

Tags:

I have a method in a rails 3 model that parses XML with nokogiri. How can I call this method in the console in order to test its out.

Here is the whole class (I'm trying to call 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 

Edit: Wow, 1000 views. I hope this question has helped people as much as it helped me. It's amazing to me when I look back on this that, little more than a year ago, I couldn't figure out the difference between instance methods and class methods. Now I am writing complex service-oriented applications and backends in ruby, Rails, and many other languages/frameworks. Stack Overflow is the reason for this. Thank you so much to this community for empowering people to solve their problems and understand their solutions.

like image 567
lightyrs Avatar asked Jan 24 '11 07:01

lightyrs


People also ask

What is call method in Rails?

call evaluates the proc or method receiver passing its arguments to it.


2 Answers

It looks like you're wanting to use this as a class method, and so you must define it like this:

def self.generate_list   ... end 

Then you can call this as Podcast.generate_list.

like image 77
Ryan Bigg Avatar answered Sep 20 '22 13:09

Ryan Bigg


From your code, it looks like your generate_list method actually builds the Podcast and saves it?

Start up the rails console: $ rails console

And create a new Podcast, calling the method on it:

> pod = Podcast.new > pod.generate_list 
like image 37
raidfive Avatar answered Sep 17 '22 13:09

raidfive