Skip to content

Instantly share code, notes, and snippets.

@luk3thomas
Last active December 15, 2015 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luk3thomas/5243493 to your computer and use it in GitHub Desktop.
Save luk3thomas/5243493 to your computer and use it in GitHub Desktop.
quick and dirty twitter api v 1.1
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