On Jun 13, 2005, at 7:31 PM, Ezra Zygmuntowicz wrote:
> Hey list-
> I''m trying to use net/http in a helper to get some html
content
> from another webserver and include it in one of my views. I am
> using this function:
>
> require ''net/http''
>
> def fetch (page)
> Net::HTTP.start("192.168.0.2") do |http|
> response = http.get("/#{page}")
> puts response.body
> end
> end
>
> and in my controller action
>
> def display
> @story = @params[:article]
> end
>
> and then in my view
> <%= fetch(@story) %>
>
> The route that handles this is
> map.connect "wrappers/*article",
> :controller => "page",
> :action => "display"
>
> And the url that would invoke this route is:
> http://localhost:3000/wrappers/283524246749711.news
>
> This works great from a command line script or from irb, It fetches
> the exact content that I want no problem. But when I have it as a
> rails helper function, it confuses the rails routes feature. As it
> fetches the page it tries to send each and every link in the
> fetched page through routing rules. Is rails doing something behind
> the scenes to my net/http requests? How could I separate this out
> into a lib or something so I can use this feature.
>
> so If I do:
>
> require ''net/http''
>
> def fetch (page)
> Net::HTTP.start("192.168.0.2") do |http|
> response = http.get("/#{page}")
> puts response.body
> end
> end
>
> puts fetch("wrappers/283524246749711.news")
>
> In a normal shell script or in irb then it works fine and gets the
> correct content. But once I try to do it within rails it falls
> apart trying to use routes for each href in the entire fetched
> page. Which eventually ends up working except that it takes a few
> seconds to render the page and there are about 20 routing error
> messages in my development log
>
>
> Help Please??
The "puts" is causing the problem, I''m pretty sure, but I
can''t quite
explain what happens with Rails and routing. You want the fetch
method to return a string containing the response, not puts to stdout
(or the HTTP response where Rails seems to direct it). Here''s a
fetch method I''ve coded recently, borrowing pretty much directly from
the PickAxe book, which also handles redirects:
def fetch(uri_str, limit=10)
fail ''http redirect too deep'' if limit.zero?
response = Net::HTTP.get_response(URI.parse(uri_str))
case response
when Net::HTTPSuccess
response
when Net::HTTPRedirection
fetch(response[''location''], limit - 1)
else
response.error!
end
end
Erik