views:

92

answers:

1

hi

I am trying to use hpricot in JRuby. My problem is the following. If I have this code:

 #!ruby
 require 'hpricot'
 require 'open-uri'
 # load the RedHanded home page
 doc = Hpricot(open("http://redhanded.hobix.com/index.html"))

where do I put it? Into my controller? Because its not accepting it there. And if I'm supposed to put it in my model. How can I call it frm my view?

Thank you

it gives me this error when trying the wired.com website

Errno::ENOENT in ProductsController#create

No such file or directory - File not found - www.wired.com

RAILS_ROOT: H:\Documents and Settings/owner/My Documents/NetBeansProjects/RailsApplication5

+1  A: 

Getting Rails to understand and see Hpricot is not very hard to do.

  1. Install Hpricot: jruby -S gem install hpricot.
  2. In your Rails app, find the config/environment.rb file
  3. Find the lines which start with config.gem in the file and add

    config.gem "hpricot", :source => "http://code.whytheluckystiff.net"

  4. Now you'll be able to use Hpricot directly from a controller as in normal (J)Ruby code. I strongly advise not to put any kind of business logic into your views and only minimal conditionals for sanity and in order to keep things straight, readable and maintainable. Or if you follow the "skinny controllers, simple views, fat models" paradigm, you may be able to refactor the code and put the Hpricot calls directly into a method inside your model class that is accessible from the view.

Some code examples are below.

Example controller RAILS_ROOT/app/controllers/example_controller.rb:

class ExampleController < ApplicationController
  def index
    @doc = Hpricot(open("http://www.wired.com"))
    # here come some very serious calculations, queries etc.
  end
end

Example view RAILS_ROOT/app/views/example/index.html.erb using the controller:

<pre>
  <%= @doc ? @doc.to_s : "There is no content at the site" %>
  <!-- blablabla -->
</pre>

As I've mentioned, you might be able to push the Hpricot(open(...)) call back to the model, but first give it a try like this. If it's working, refactor :)

Tamás Mezei
it still gives me a "No such file or directory - File not found" error :S:S
Lily
btw thanks so much :)
Lily
Yeah, that hobix.com website link doesn't work, so try something more popular, like www.wired.com for the URL. Please, update your question with the full error message and stack trace, if possible.
Tamás Mezei