Koala Ruby Library
repository·master·Indexed 25 days ago
https://github.com/arsduo/koalaA lightweight Ruby library for interacting with the Facebook Graph API, Marketing API, and Atlas API. It provides support for batch requests, photo and video uploads, real-time updates, OAuth validation, and pagination via GraphCollection. The library includes utilities for managing app access tokens, creating test users, and monitoring rate limits, utilizing Faraday for HTTP requests.
What's inside Koala
- You can install Koala using Bundler or by installing the gem directly via the command line.
Configure Koala global settings
masterTo avoid providing credentials for every request, you can configure Koala with global settings. In a Rails application, it is recommended to place this configuration in
config/initializers/koala.rb.Note: Global configuration is not currently threadsafe.
Koala.configure do |config| config.access_token = MY_TOKEN config.app_access_token = MY_APP_ACCESS_TOKEN config.app_id = MY_APP_ID config.app_secret = MY_APP_SECRET endConfigure HTTP/Faraday settings
masterKoala uses Faraday for HTTP requests. You can configure Faraday options globally viaKoala.http_service.http_optionsor pass them on a per-request basis using therequestkey in the options hash.Execute Batch API requests
masterYou can perform multiple API calls in a single request using the
batchmethod. You can also pass a post-processing block to each method within the batch to modify results or consume data in place.# Standard batch @graph.batch do |batch_api| batch_api.get_object('me') batch_api.put_wall_post('Making a post in a batch.') end # Batch with post-processing to consume data in place @graph.batch do |batch_api| batch_api.get_object('me') {|me| self.about_me = me } batch_api.get_connections('me', 'photos') {|photos| self.photos = photos } endHandle Real-time Updates with RealtimeUpdates
masterThe
Koala::Facebook::RealtimeUpdatesclass allows you to subscribe to, list, and unsubscribe from real-time updates for specific Facebook objects. It also includes a helper to verify callback URLs.@updates = Koala::Facebook::RealtimeUpdates.new(app_id: app_id, secret: secret) # Subscribe to field changes @updates.subscribe("user", "first_name, last_name", callback_url, verify_token) # List current subscriptions @updates.list_subscriptions # Unsubscribe @updates.unsubscribe("user") # Respond to Facebook's verification challenge # Returns the hub.challenge parameter if verify_token matches Koala::Facebook::RealtimeUpdates.meet_challenge(params, your_verify_token)Manage App Access Tokens and Signed Requests
masterUse
Koala::Facebook::OAuthto obtain application access tokens (useful for subscriptions) and to parse signed requests from Facebook.@oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url) # Get app access token @oauth.get_app_access_token # Parse signed requests @oauth.parse_signed_request(signed_request_string)Paginate through GraphCollection results
masterWhen calling methods that return arrays (like
get_connectionsorsearch), Koala returns aGraphCollection. This object allows you to iterate through results and fetch subsequent pages.# Returns a GraphCollection feed = @graph.get_connections("me", "feed") feed.each {|f| do_something_with_item(f) } # Get the next page of results next_feed = feed.next_page # Alternatively, use page parameters to fetch a page manually next_page_params = feed.next_page_params page = @graph.get_page(next_page_params)Create Test Users
masterUse
Koala::Facebook::TestUsersto create fake users or entire networks of users for testing purposes.@test_users = Koala::Facebook::TestUsers.new(app_id: id, secret: secret) # Create a single user user = @test_users.create(is_app_installed, desired_permissions) # Create a network of users @test_users.create_network(network_size, is_app_installed, common_permissions)Use the Graph API with Koala::Facebook::API
masterThe
Koala::Facebook::APIclass provides the interface to Facebook's data. You can initialize it with anaccess_tokenor rely on global configuration. For extra security, you can provide anapp_secretto tie access tokens to your app secret.require 'koala' # Initialize with token @graph = Koala::Facebook::API.new(access_token) # Basic operations profile = @graph.get_object("me") friends = @graph.get_connections("me", "friends") @graph.put_connections("me", "feed", message: "I am writing on my wall!") # Three-part queries @graph.get_connections("me", "mutualfriends/#{friend_id}") # Secure initialization @graph = Koala::Facebook::API.new(access_token, app_secret) # Specifying API version (globally or per-request) Koala.config.api_version = "v2.0" @graph.get_object("me", {}, api_version: "v2.0")Monitor Facebook Rate Limits
masterRate limit information can be accessed via
Facebook::APIErrorattributes or by configuring a globalrate_limit_hookinKoala.configure.# Access via error object error.fb_buc_usage error.fb_ada_usage error.fb_app_usage # Access via global hook Koala.configure do |config| config.rate_limit_hook = ->(limits) { limits["x-app-usage"] limits["x-ad-account-usage"] limits["x-business-use-case-usage"] } end # Access via per-API configuration Koala::Facebook::API.new('', '', ->(limits) {})Make a manual HTTP request
masterUseKoala.make_requestas a convenient alias toKoala.http_service.make_request. It allows you to execute a request directly through the configured HTTP service.Check if content is binary using UploadableIO.binary_content?
masterThe class methodKoala::HTTPService::UploadableIO.binary_content?(content)determines if the providedcontentis a binary payload. It returnstrueif the content is an instance ofUploadableIOor if it matches recognized file parameter patterns (Rails 3, Sinatra, or standard File/Tempfile objects).