Koala Ruby Library

repository·master·Indexed 25 days ago

https://github.com/arsduo/koala

A 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.

Tokens
6.7K
Snippets
9
Records
53
Agent score
86%

What's inside Koala

  1. Configure Koala global settings

    master

    To 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
    end
  2. Configure HTTP/Faraday settings

    master
    Koala uses Faraday for HTTP requests. You can configure Faraday options globally via Koala.http_service.http_options or pass them on a per-request basis using the request key in the options hash.
  3. Execute Batch API requests

    master

    You can perform multiple API calls in a single request using the batch method. 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 }
    end
  4. Handle Real-time Updates with RealtimeUpdates

    master

    The Koala::Facebook::RealtimeUpdates class 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)
  5. Manage App Access Tokens and Signed Requests

    master

    Use Koala::Facebook::OAuth to 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)
  6. Paginate through GraphCollection results

    master

    When calling methods that return arrays (like get_connections or search), Koala returns a GraphCollection. 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)
  7. Create Test Users

    master

    Use Koala::Facebook::TestUsers to 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)
  8. Use the Graph API with Koala::Facebook::API

    master

    The Koala::Facebook::API class provides the interface to Facebook's data. You can initialize it with an access_token or rely on global configuration. For extra security, you can provide an app_secret to 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")
  9. Monitor Facebook Rate Limits

    master

    Rate limit information can be accessed via Facebook::APIError attributes or by configuring a global rate_limit_hook in Koala.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) {})
  10. Check if content is binary using UploadableIO.binary_content?

    master
    The class method Koala::HTTPService::UploadableIO.binary_content?(content) determines if the provided content is a binary payload. It returns true if the content is an instance of UploadableIO or if it matches recognized file parameter patterns (Rails 3, Sinatra, or standard File/Tempfile objects).