Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Application oauth2 for Twitter using Ruby
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