Created
October 21, 2014 18:56
-
-
Save coderberry/4afc7ec0beaad30f4015 to your computer and use it in GitHub Desktop.
Application oauth2 for Twitter using Ruby
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 'oauth' | |
require 'httpclient' | |
require 'json' | |
class SimpleTwitter | |
def initialize(config) | |
@config = config | |
@http_client = HTTPClient.new | |
end | |
def encoded_token | |
bearer_token_credentials = "#{@config[:key]}:#{@config[:secret]}" | |
Base64.encode64(bearer_token_credentials).split(/\n/).join('') | |
end | |
def authorization_headers | |
{ | |
'Authorization' => "Basic #{encoded_token}", | |
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8' | |
} | |
end | |
def get_user_timeline(username, max=10) | |
access_token = get_bearer_token | |
uri = URI.parse("https://api.twitter.com/1.1/statuses/user_timeline.json?count=#{max}&screen_name=#{username}") | |
headers = { | |
'User-Agent' => 'My Twitter App v1.0.23', | |
'Authorization' => "Bearer #{access_token}", | |
'Accept-Encoding' => 'gzip' | |
} | |
response = @http_client.get(uri, {}, headers) | |
gz = Zlib::GzipReader.new(StringIO.new(response.body.to_s)) | |
return JSON.parse(gz.read) | |
end | |
def get_bearer_token | |
uri = URI.parse('https://api.twitter.com/oauth2/token') | |
response = @http_client.post(uri, { grant_type: 'client_credentials' }, authorization_headers) | |
return JSON.parse(response.body)['access_token'] | |
end | |
end | |
twitter = SimpleTwitter.new({ key: ENV['CONSUMER_KEY'], secret: ENV['CONSUMER_SECRET'] }) | |
results = twitter.get_user_timeline('coderberry') | |
puts results.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment