Created
March 20, 2013 18:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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