Skip to content
David Curtis edited this page Jul 6, 2017 · 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.

HTTP Libraries

Koala uses Farady, which means that 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 in turn 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
  # request_object is a Koala::HTTPService::Request object as of 3.0
  def self.make_request(request_object)
    before_stuff
    # make the request
    # result is a Koala::HTTPService::Result object
    result = Koala::HTTPService.make_request(request)
    after_stuff
    result
   end
end

Koala.http_service = MyHTTPService

Simple!

Faraday middleware

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.