9.4. Consuming Web Services
Although ActiveResource is a convenient and useful way of consuming RESTful web services, you still need a way to use services that are not RESTful. You'll often need to hit something that is stored at a particular URL and that is delivered via XML. Hitting an RSS or Atom feed is a particular example of that kind of interaction.
Although there are modules that allow you to specifically parse RSS and Atom files as things in their own right, it's significantly easier to just treat them the same as any other XML file and use the Ruby Standard Library's REXML toolkit. REXML can also be used to generate XML documents, although I'm not going to be focusing on that functionality here.
Starting with an XML document is straightforward:
require 'rexml/document' document = REXML::Document.new(source)
The source can be one of three things: another REXML::Document instance, a string that is itself a valid XML document to be parsed, or a file containing a valid XML document (of course, the file is duck typed, so any object that responds to the same messages as a file will work just fine). For our purposes, the input is most likely to be a URL, which you can access via the Ruby Net::HTTP library. The Net::HTTP library doesn't let you treat the remote URL as a file, but it does let you programmatically execute an HTTP request as follows and receive the result as a string:
Net::HTTP.get(URI.parse(url))
The arguments to the get method are either a single argument that ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access