Friday, November 24, 2006

[temp] Pages 125-6: Talking to networks


Listen to this article.

Value: Medium

Level: Average

Summary:
In the socket library Ruby provides you a set of classes to access TCP, UDP, SOCKS, Unix domain sockets, and more. The lib/net set of library modules provides handlers for a set of application-level protocols (currently FTP, HTTP, POP, SMTP, and telnet). By bringing the open-uri library into a program, the Kernel#open() method suddenly recognizes http:// and ftp:// URLs in the filename, and handles redirects automatically.

Memo: Use the open-uri library, and Kernel#open() will open URL (only http and ftp), automatically handling "404" errors and redirects, too.

Example:

You can list the images that are displayed on the Pragmatic Programmer home page in this way...

require 'net/http'
h = Net::HTTP.new(' www.pragmaticprogrammer.com', 80)
response = h.get('/index.html', nil)
if response.message == "OK"
puts response.body.scan(/<img src="(.*?)"/m).uniq
end

...or in this shorter, safer, smarter way

require 'open-uri'
open('http://www.pragmaticprogrammer.com') do |f|
puts f.read.scan(/<img src="(.*?)"/m).uniq
end

Reported errata (at 10/17/06 14:17:18 PDT): 0

Errata I found: 0

My suggestions to the author : 0

0 Comments:

Post a Comment

<< Home