Last active
December 15, 2015 10:09
-
-
Save luk3thomas/5243493 to your computer and use it in GitHub Desktop.
quick and dirty twitter api v 1.1
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
class Twitter | |
require 'uri' | |
require 'base64' | |
require 'open-uri' | |
require 'net/http' | |
def self.tweets count = 7 | |
begin | |
data = self.parse(`curl -s -H "#{authorization("Bearer", access_token)}" "https://api.twitter.com/1.1/statuses/user_timeline.json?count=#{count}&screen_name=TEST&exclude_replies=true"`) | |
rescue | |
data = [] | |
end | |
self.to_json(data) | |
end | |
def self.access_token | |
token = escape("TOKEN") | |
token_secret = escape("SECRET") | |
encoded = self.encode([token, token_secret]) | |
response = self.parse(`curl -s -d "#{self.body}" -H "#{self.authorization("Basic", encoded)}" -H "#{self.content_type}" "https://api.twitter.com/oauth2/token"`) | |
response["access_token"] | |
end | |
def self.body | |
"grant_type=client_credentials" | |
end | |
def self.content_type | |
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8" | |
end | |
def self.authorization type, key | |
"Authorization: #{type} #{key}" | |
end | |
private | |
def self.escape str | |
URI.escape(str) | |
end | |
def self.encode arr, sep = ":" | |
# not sure why, but the encoded token is two lines, join the two | |
# lines so the request goes through | |
Base64.encode64(arr.join(':')).split("\n").join('') | |
end | |
def self.parse str | |
begin | |
ActiveSupport::JSON.decode(str) | |
rescue | |
end | |
end | |
def self.to_json str | |
begin | |
ActiveSupport::JSON.encode(str) | |
rescue | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment