views:

280

answers:

3

I know this might be a dumb question. I'm trying to use this xml parser

http://nokogiri.rubyforge.org/nokogiri/Nokogiri.html

I've put the code below in a controller in a bringRSS method(?), and it works fine in IRB. But how do I get values for puts link.content into my views

 def bringRSS

  require 'nokogiri'
  require 'open-uri'

  # Get a Nokogiri::HTML:Document for the page we’re interested in...

  doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))


  # Do funky things with it using Nokogiri::XML::Node methods...

  ####
  # Search for nodes by css
  doc.css('h3.r a.l').each do |link|
    puts link.content

  end

  ####
  # Search for nodes by xpath
  doc.xpath('//h3/a[@class="l"]').each do |link|
    puts link.content
  end

  ####
  # Or mix and match.
  doc.search('h3.r a.l', '//h3/a[@class="l"]').each do |link|
    puts link.content
  end


 end
A: 

The use of puts in a Rails action will throw an exception.

Instead just assign the data to an instance variable, like this:

@link_content = []
...
doc.css('h3.r a.l').each do |link|
    @link_content << link.content
end
...

You can access it later in your views with the same name

Carmine Paolino
+3  A: 

Your method is a rails action ? If so, the "puts" method is inappropriate. You should define some global vars that'll be accessible in the view.

@css_content = Array.new
doc.css('h3.r a.l').each do |link|
    @css_content << link.content
end

You define an @css_content array which contains every of your links. And in your view you can use that var just like you usually use them in views.

Damien MATHIEU
thanks it worked, not sure what you mean by a "rails action", is that a special term for something?
conspirisi
In rails you have models, controllers, actions and views. That's the principle of MVC.
Damien MATHIEU
+1  A: 

Technically, you could write directly to your response, as it behaves more or less like the object you puts to in IRB. But as mentioned above, the Rails way of doing it is to use the controller to assign to instance vars and your view to render them.

As a benefit, you'll be able to use some really nice Ruby when assigning:

@links = doc.css('h3.r a.l').map{|link|link.content}

will map what each object's content method returns, just like you did above. And since Rails extends this by giving symbol objects a to_proc method, you could shorten it to

@links = doc.css('h3.r a.l').map(&:content)
zmalltalker
thanks got to to_proc method just yet :), but I'll refer back to this when I get there
conspirisi
Damien MATHIEU
The readability of turning a symbol into a proc was a really hot topic around the time it was introduced; it actually made it into core Ruby in 1.9. Pretty? No. Practical? Yes.
zmalltalker