-
Notifications
You must be signed in to change notification settings - Fork 464
Extensions
One of my goals in writing Koala is to make a library anyone can use. In particular, I didn’t want to tie the library to a particular mechanism for making network requests to Facebook. Typhoeus may be our library of choice at Context Optional, 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 string for JSON parsing 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. Voila! You’re done.
(You can check out lib/http_services.rb to see how the built-in HTTP modules are designed.)
This works because all the methods we just saw are wrappers for a method named api, which makes and parses the request. 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") # other code.... # make the request via the provided module's make_request method result = Koala.make_request(path, args, verb) # other code.... end
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.
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’.