Skip to content

Instantly share code, notes, and snippets.

@upvalue
Created May 15, 2013 21:25
Show Gist options
  • Save upvalue/5587523 to your computer and use it in GitHub Desktop.
Save upvalue/5587523 to your computer and use it in GitHub Desktop.
Non-intrusive social sharing tags for Jekyll. Note: uses deprecated/private APIs, probably against TOS or whatever
# likes.rb - non intrusive sharing tags for jekyll/liquid
# usage (unfortunately rather verbose because of liquid)
# {{ site.url | append: page.url | facebook_likes }} => Fixnum
# {{ site.url | append: page.url | facebook_share_link }} => a link to share this page
# {{ site.url | append: page.url | twitter_tweets }} => Fixnum
# {{ site.url | append: page.url | twitter_share_link }} => Fixnum
# if you're doing it a lot, try something like this
# {% assign absolute = site.url | append: page.url %}
# NOTE: twitter ignores localhost urls. if you try to tweet one, the url will not appear in your tweet
require 'cgi'
require 'open-uri'
require 'json'
module Jekyll
module Filters
# Configuration, change to your liking
@@likes_production = Proc.new { |context| context.registers[:site].config[:production] == true }
@@facebook_share_link_proc = Proc.new { |url,likes| "<a class=\"btn btn-mini btn-primary\" href=\"https://facebook.com/sharer/sharer.php?u=#{CGI::escape(url)}\";><i class=\"icon-facebook\"></i> Like (#{likes})</a>" }
@@twitter_share_link_proc = Proc.new { |url,text,tweets| "<a class=\"btn btn-mini btn-primary\" href=\"https://twitter.com/share?url=#{url}&text=#{CGI::escape(text)}\"><i class=\"icon-twitter\"></i> Tweet (#{tweets})</a>" }
# "Caching"
@@facebook_like_cache = {}
@@twitter_tweet_cache = {}
def facebook_likes(input)
unless @@likes_production.call(@context) then return 0 end
if @@facebook_like_cache[input] then return @@facebook_like_cache[input] end
uri = "https://api.facebook.com/method/fql.query?format=json&query=select%20%20like_count%20from%20link_stat%20where%20url%20=%20'#{input}'"
rawjson = open(uri).read
json = JSON.parse(rawjson)
likes = (json and json.size > 0) ? json[0]['like_count'] : 0
@@facebook_like_cache[input] = likes
return likes
end
def facebook_share_link(url)
@@facebook_share_link_proc.call(url, facebook_likes(url))
end
def twitter_tweets(input)
unless @@likes_production.call(@context) then return 0 end
if @@twitter_tweet_cache[input] then return @@twitter_tweet_cache[input] end
uri = "http://urls.api.twitter.com/1/urls/count.json?url=#{input}"
rawjson = open(uri).read
json = JSON.parse(rawjson)
count = (json and json.size > 0) ? json['count'] : 0
@@twitter_tweet_cache[input] = count
count
end
def twitter_share_link(url, text)
@@twitter_share_link_proc.call(url, text, twitter_tweets(url))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment