Getting Rails to understand and see Hpricot is not very hard to do.
- Install Hpricot:
jruby -S gem install hpricot
.
- In your Rails app, find the
config/environment.rb
file
Find the lines which start with config.gem
in the file and add
config.gem "hpricot", :source => "http://code.whytheluckystiff.net"
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 :)