Skip to content

Instantly share code, notes, and snippets.

@boof
Last active December 10, 2015 15:18
Show Gist options
  • Save boof/4452876 to your computer and use it in GitHub Desktop.
Save boof/4452876 to your computer and use it in GitHub Desktop.
Facebook::Profile to introduce current_user
current_user.likes? Application.object_key
module Facebook
class Cache < Struct.new(:graph)
# Invalide cache after 10 minutes
#
# For automatic invalidation, see
# https://developers.facebook.com/docs/reference/api/realtime/
TTL = 10.minutes
def self.new(graph, key)
key.to_s == 'me' ? graph : super(graph)
end
attr_accessor :ttl
def initialize(graph)
super graph
@ttl = TTL
end
# Koala::Facebook::API
def get_connections(key, k)
fetch(key, 'connections', k) { graph.get_connections key, k }
end
def get_picture(key)
fetch(key, 'picture_url') { graph.get_picture key }
end
def get_object(key)
fetch(key, 'object') { graph.get_object key }
end
protected
def fetch(*a)
Rails.cache.fetch(['fb', *a] * ':', expires_in: @ttl) { yield }
end
end
class Object
# includes some ActiveModel modules
# Returns instance with graph object for token set
def self.connect(token, object_key)
new Koala::Facebook::API.new(token), object_key
end
# Allow to inject graph object for stubbing
def initialize(graph, key)
@graph, @key = Cache.new(graph, key), key
@cache = Hash.new { |h, k| h[k] = @graph.get_connections key, k }
end
# getter for common properties
def id
object.fetch 'id'
end
def name
object.fetch 'name'
end
protected
def connections(type)
Enumerator.new { |y| @cache[type].each { |c| y << c } }
end
def object
@object ||= @graph.get_object @key
end
end
class Profile < Facebook::Object
# includes some ActiveModel modules
# be aware that 'me' cannot be cached
def self.me(token)
connect token, 'me'
end
def picture_url
@picture_url ||= @graph.get_picture id.to_s
end
# common query methods
def likes? cid
connections('likes').any? { |c| c.fetch('id') == cid }
end
require 'active_support/concern'
module Extension
extend ActiveSupport::Concern
included do
cattr_accessor :fb_token, :fb_key
delegate :likes?, :picture_url, to: profile
end
def profile
Facebook::Profile.connect \
read_attribute(fb_token), read_attribute(fb_key)
end
end
module ClassMethods
def has_profile(options = {})
include Facebook::Profile::Extension
self.fb_token = options.fetch :token_column, :facebook_token
self.fb_key = optione.fetch :key_column, :facebook_id
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment