Skip to content
Hans Lemuet edited this page Jan 15, 2014 · 20 revisions

One of our goals in writing Koala is to make a library anyone can use and that anyone can extend. In particular, we didn’t want to tie the library to a particular mechanism for making network requests to Facebook, and we wanted to make it easy to hook into Koala to meet your specific needs.

If you need something that Koala doesn’t supply out of the box, there are several ways to extend the library.

Changes with 1.2

Originally, we implemented a homebrew set of HTTPService modules, which could be used to make requests from Typhoeus or Net::HTTP. With 1.2, we’ve switched Koala over to Faraday, a modular, Rack-like library for making HTTP requests. This will be an entirely transparent change for most users, unless you’ve done development against our old HTTPService infrastructure. If you have, or if you want to, read on for more information on how Koala works as of 1.2.

HTTP Libraries

With Koala (1.2beta and beyond), you can use any of the HTTP libraries Faraday supports out of the box; if your preferred library isn’t supported yet, you can also write your own adapter. The Typhoeus module is a good example of how Faraday adapters are structured.

To change the HTTP library Koala/Faraday uses, just define Faraday.default_adapter somewhere in your code:

Faraday.default_adapter = :typhoeus
Faraday.default_adapter = :your_library

Hooking into Koala’s requests

If you want to hook into Koala’s request-making process, there are two ways to do it — wrapping the make_request method or writing a Faraday middleware.

make_request

Koala channels all requests through the Koala.make_request method, which then (after 1.2beta) calls Koala::HTTPService.make_request. If you want to implement request logging, add more sophisticated timeout handling, analyze request parameters or results, etc., the easiest way is to subclass HTTPService and override the make_request method:

module MyHTTPService
  include Koala::HTTPService
  def self.make_request(path, args, verb, options = {})
    before_stuff
    # make the request
    result = Koala::HTTPService.make_request(path, args, verb, options)
    # return the body of the result as a Koala::Response object
    after_stuff
    result
   end
end

Koala.http_service = MyHTTPService

Simple!

Faraday middlware

If you want to reuse your code in other places (your own Faraday requests, the Twitter gem, etc.), writing Faraday middleware is the way to go. Writing middleware is more complicated than wrapping the HTTPService, but potentially more powerful. To get a sense of how Faraday middleware works, check out the JSON middleware as an example. (At some point we’ll add some examples here.)

Clone this wiki locally