I've been working my way through Why's (Poignant) Guide to Ruby. In Chapter 6, _why guides the reader through interacting with a simple web service ("the Preeventualist’s Losing and Finding Registry") using open-uri:
SEARCHING
========= To search for lost items, use the following address:http://preeventualist.org/lost/search?q={search word}
You may replace {search word} with your search term. For example, to search for "cup":
http://preeventualist.org/lost/search?q=cup
You will be given a list of cups which have been lost or found.
If you want to search for only lost cups or only found cups, use the 'searchlost' and 'searchfound' pages:
http://preeventualist.org/lost/searchlost?q=cup
Which does not work.
The original static content of The Preeventualist has been mirrored at _why's Estate, but unfortunately the search service has not been configured:
http://viewsourcecode.org/why/preeventualist/search?q=bacon
Is there a working mirror of _why's former preeventualist web service anywhere? If not, what about a comparable analog: a service that returns newline separated raw-text list开发者_高级运维s in response to different searches?
https://github.com/mistydemeo/preeventualist
Apparently, mistydemeo has recreated the entire specs according to chapter 6 from _why's poignant guide.
This reborn version of the service is 100% compatible with the API specified in the Poignant Guide, but also adds some new features like JSON and Brooklyn Integer support.
Open-URI itself is very easy to use, and, if you think about it, almost every website out there qualifies as returning the sort of file you're talking about, though it will be HTML, which is text with line-breaks (usually).
As an example, try:
require 'open-uri'
body_ios = open('http://www.iana.org/domains/example/')
puts body_ios.lines.first
which will output:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
That's a separate line of text.
What's missing from _Why's examples are passing queries, but, again, if you understand how queries work in a normal URL, like when used in a browser, then there isn't anything new or unique about doing it with Open-URI. You request the URL, the server returns the results, and Open-URI returns it to you as an IO stream that you can read, or treat as you would other IO streams.
Open-URI is very flexible and makes it easy to read a page or file remotely. It handles redirections transparently also, which is nice.
As you progress, you might want something with more flexibility, and, in that case I'll recommend the Typhoeus, HTTPClient or Patron gems.
精彩评论