Skip to content
arsduo edited this page Dec 23, 2010 · 20 revisions

One of our goals in writing Koala is to make a library anyone can use. In particular, we didn’t want to tie the library to a particular mechanism for making network requests to Facebook. Typhoeus may be our library of choice, but Koala doesn’t really care if you’d rather use Curb or HTTParty or just plain old Net::HTTP.

Using Koala with another HTTP library is simple — just write a really quick module defining one class method called make_request:

def self.make_request(path, args, verb)
  # make the request
  # return the body of the result as a Koala::Response object
  Koala::Response.new(http_status, response_body, header_hash)
 end

When Koala is loaded, it checks to see if Typhoeus is installed; if not, it silently falls back to Net::HTTP for requests. To use your module instead, just call

Koala.http_service = YourModule

The http_service= method will include your module, overwriting the existing make_request method. (You can check out lib/http_services.rb to see how the built-in HTTP modules are designed.)

Voila! You’re done.

How it works

All the methods in the API classes are ultimately wrappers for a method named api, which makes a request and parses the response. In everyday life you probably won’t need to access the api method directly, but it’s important to know in case you want to extend Koala to use a different HTTP library.

def api(path, args = {}, verb = "get", options = {}, &error_checking_block)
  # ...other code...
  # make the request via the provided service
  result = Koala.make_request(path, args, verb, options)
  # ...other code...
  # now return the desired information
  if options[:http_component]
    result.send(options[:http_component])
  else
    result.body
  end
end

There’s a lot of interesting stuff going on in that method, but what you really need to remember when writing an HTTP service module is that it offer a make_request method with the above signature and return a Koala::Response instance.

Other Ideas
 

Request logging and the like

You can also use the same mechanism to implement request logging. Just stick some logging inside the make_request method — you can even call super to actually send the request. You can track what calls are made, how long they take, whatever you find useful.

Timeouts

Whether you’re using timeout.rb or SystemTimer, you can easily wrap the make_request method to achieve your desired timeout behavior.

Koala inside other libraries

Since Koala just implements a basic wrapper for the Graph API, there’s no reason Koala couldn’t be used inside any other systems, including other Facebook libraries that provide higher-level data encapsulation and convenience methods. Just sayin’.

Clone this wiki locally