Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Building high quality software is about more than just solving a particular problem. Instead, it is important to try to make sure that the tools you build fit their problem domain as naturally as possible. As an example, we can consider the task of downloading the contents of a single webpage which is protected by HTTP Basic Authentication.
Net::HTTP standard library is one possible option:
require "net/http" uri = URI('http://browserspy.dk/password-ok.php') req = Net::HTTP::Get.new(uri.request_uri) req.basic_auth 'test', 'test' content = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end puts content.body
This approach clearly gets the job done, and if evaluated on its own may seem suitable for the task. However, the
OpenURI solution shown below solves this problem in a very different way:
require "open-uri" content = open("http://browserspy.dk/password-ok.php", :http_basic_authentication => ['test','test']) puts content.read
The difference between these two tools is that
Net::HTTP is meant primarily to be a low level wrapper around the HTTP protocol, while the
OpenURI library focuses on the most common problems and presents a more simple API for those operations. This makes it a more suitable tool to use when our needs are simple, as they are here. However, as soon as our network interactions get more complex,
Net::HTTP becomes the better solution. This scenario shows just how dependent on context suitability is.
Turn the page if you're taking the linear tour, or feel free to jump around via the sidebar.