Skip to content

Instantly share code, notes, and snippets.

@fdv
Created March 20, 2013 18:51
Show Gist options
  • Save fdv/5207375 to your computer and use it in GitHub Desktop.
Save fdv/5207375 to your computer and use it in GitHub Desktop.
A quick way to get your Twitter followers counter in Ruby (designed for Rails application), with cache system and error handling.
require 'open-uri'
require 'json'
def get_twitter_counter
url = 'http://api.twitter.com/1/users/show.json?screen_name=fdevillamil'
cache = File.join(Rails.root, "tmp", "twitter_counter")
return File.read(cache) if File.exists?(cache) && (Time.now - File.mtime(cache)).to_i < 7200
begin
open(url) {|http| @json = JSON.parse(http.read)}
File.open(cache, 'w') {|f| f.write(@json['followers_count']) }
rescue
return 0
end
return @json['followers_count']
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment