lightyrs
lightyrs

Reputation: 2839

How to call rails 3 model method in the console

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.

Upvotes: 26

Views: 24502

Answers (4)

Julio Santos
Julio Santos

Reputation: 3895

Or, if you don't want to rewrite your code, follow this.

Type rails c on the terminal to open the console, then just do:

p = Podcast.new
p.generate_list

Upvotes: 3

raid5ive
raid5ive

Reputation: 6642

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

Upvotes: 15

Ryan Bigg
Ryan Bigg

Reputation: 107728

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.

Upvotes: 26

apneadiving
apneadiving

Reputation: 115541

It's an instance method so try:

Podcast.first.generate_list

You should make a class method by declaring it as follows:

def self.generate_list

And call it:

Podcast.generate_list

Upvotes: 1

Related Questions