Skip to content

Instantly share code, notes, and snippets.

@serradura
Forked from anonymous/fb_public.rb
Last active December 10, 2015 00:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save serradura/4354594 to your computer and use it in GitHub Desktop.
Save serradura/4354594 to your computer and use it in GitHub Desktop.
Two clients: HGet (easy way to have Net::HTTP responses supports HTTP and HTTPS) and FGraph (shortcut to do Facebook Graph API requests)
# Examples:
# client = FGraph.new("USERNAME")
#
# if you need see response details use:
# client.request # returns a Net::HTTPFound instance, with this you can see the status, headers# Examples:
# client = FGraph.new("USERNAME")
#
# client.data # returns the parsed response body
# if you need an alias to get the api data response, use:
# FGraph.get_data("USERNAME") # returns the Graph API public data
# Supports requests using access_token and another parameters
#
# params = {access_token: "YOUR_ACESS_TOKEN", fields: %w[id,name]}
#
# client = FGraph.new("USERNAME", params)
# or
# FGraph.get_data("USERNAME", params)
#
# Example to extend an user access token (http://developers.facebook.com/docs/howtos/login/extending-tokens/):
#
# FGraph.get('oauth/access_token', {
# protocol: 'https',
# grant_type: 'fb_exchange_token',
# client_id: 'APP_ID',
# client_secret: 'APP_SECRET',
# fb_exchange_token: 'ACCESS_TOKEN'
# }) do |client|
# client.response.body
# end
require_relative "hget"
require 'json'
class FGraph
attr_reader :path, :response
def self.get(path, params = {})
client = self.new(path, params)
client.request
if block_given?
yield client
else
return client
end
end
def self.get_data(path, params = {})
self.get(path, params) do |client|
client.data
end
end
def initialize(path, params = {})
@path = path
@protocol = params.delete(:protocol)
@params = params
end
def client
@client ||= HGet.new(uri)
end
def request
@response ||= client.request
end
def response
client.response
end
def data
raise NoData, 'Execute the #request method to fetch the API response' unless response
@data ||= JSON.parse(response.body)
end
def uri
@uri ||= begin
protocol = https? ? 'https' : 'http'
build_url(protocol, "#{path}?#{query_params}")
end
end
def access_token?
!(access_token.nil? || access_token.empty?)
end
def access_token
@params[:access_token]
end
def query_params
QueryBuilder.generate_with(@params)
end
private
def https?
access_token? || @protocol == 'https'
end
def build_url(protocol, _path)
"#{protocol}://graph.facebook.com/#{_path}"
end
end
class FGraph
class QueryBuilder
class << self
def generate_with(params)
params.map { |key, value|
if value.instance_of? Array
generate_with(value.map{ |element| [key, element] })
else
value.nil? ? escape(key) : "#{escape(key)}=#{escape(value)}"
end
}.join("&")
end
def escape(value)
URI.escape(value.to_s)
end
end
end
end
class FGraph
class NoData < RuntimeError; end
end
# Examples:
# client = HGet.new("http://graph.facebook.com/USERNAME")
# client.request # returns a Net::HTTPFound instance, with this you can see the status, headers and the body
# Supports Https requests
# HGet.new("https://graph.facebook.com/USERNAME?access_token=YOUR_ACCESS_TOKEN")
require "net/https"
require "uri"
class HGet
attr_reader :url, :response
def initialize(url)
@url = url
end
def https?
!(url.match(/https:\/\//).nil?)
end
def uri
@uri ||= URI.parse(@url)
end
def request
@response ||= http.request(Net::HTTP::Get.new(uri.request_uri))
end
def http
@http ||= begin
client = Net::HTTP.new(uri.host, uri.port)
if https?
client.verify_mode = OpenSSL::SSL::VERIFY_NONE
client.use_ssl = true
end
client
end
end
end
@serradura
Copy link
Author

Example of code that catch the id and username for the existents usernames and store the username to another status.

usernames = %w[cocacola pepsi]

access_token = "YOUR_ACCESS_TOKEN"
# get one using the graph api explorer: 
# http://developers.facebook.com/tools/explorer

usernames.inject({}) do |_report, username|
  begin
    client = FGraph.new(username, access_token: access_token)

    if client.response.code == '200'
      (_report['200'] ||= []) << {
          id: client.data['id'], 
          username: client.data['username']
        }
    else
      (_report[client.response.code] ||= []) << username
    end
  end

  _report
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment