Skip to content

Commit

Permalink
Move get/post from Twitter::REST::Client to Twitter::REST::Request
Browse files Browse the repository at this point in the history
  • Loading branch information
sferik committed Nov 6, 2014
1 parent a46d9f2 commit 65773c7
Show file tree
Hide file tree
Showing 27 changed files with 300 additions and 255 deletions.
16 changes: 8 additions & 8 deletions lib/twitter/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def initialize(options = {})
instance_variable_set("@#{key}", value)
end
yield(self) if block_given?
validate_credential_type!
validate_credentials!
end

# @return [Boolean]
Expand Down Expand Up @@ -52,23 +52,23 @@ def credentials?
credentials.values.all?
end

def oauth_auth_header(method, uri, options = {})
uri = Addressable::URI.parse(uri)
SimpleOAuth::Header.new(method, uri, options, credentials)
end

private

# Ensures that all credentials set during configuration are of a
# valid type. Valid types are String and Boolean.
#
# @raise [Twitter::Error::ConfigurationError] Error is raised when
# supplied twitter credentials are not a String or Boolean.
def validate_credential_type!
def validate_credentials!
credentials.each do |credential, value|
next if value.nil? || value == true || value == false || value.is_a?(String)
fail(Twitter::Error::ConfigurationError.new("Invalid #{credential} specified: #{value.inspect} must be a string."))
fail(Twitter::Error::ConfigurationError.new("Invalid #{credential} specified: #{value.inspect} must be a String."))
end
end

def oauth_auth_header(method, uri, params = {})
uri = Addressable::URI.parse(uri)
SimpleOAuth::Header.new(method, uri, params, credentials)
end
end
end
5 changes: 2 additions & 3 deletions lib/twitter/cursor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,19 @@ class Cursor

# Initializes a new Cursor
#
# @param attrs [Hash]
# @param key [String, Symbol] The key to fetch the data from the response
# @param klass [Class] The class to instantiate objects in the response
# @param request [Twitter::REST::Request]
# @return [Twitter::Cursor]
def initialize(attrs, key, klass, request)
def initialize(key, klass, request)
@key = key.to_sym
@klass = klass
@client = request.client
@request_method = request.verb
@path = request.path
@options = request.options
@collection = []
self.attrs = attrs
self.attrs = request.perform
end

private
Expand Down
2 changes: 2 additions & 0 deletions lib/twitter/rest/api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

module Twitter
module REST
# @note All methods have been separated into modules and follow the same grouping used in {http://dev.twitter.com/doc the Twitter API Documentation}.
# @see https://dev.twitter.com/overview/general/things-every-developer-should-know
module API
include Twitter::REST::DirectMessages
include Twitter::REST::Favorites
Expand Down
50 changes: 18 additions & 32 deletions lib/twitter/rest/client.rb
Original file line number Diff line number Diff line change
@@ -1,31 +1,25 @@
require 'base64'
require 'faraday'
require 'faraday/request/multipart'
require 'json'
require 'timeout'
require 'twitter/client'
require 'twitter/error'
require 'twitter/rest/api'
require 'twitter/rest/request'
require 'twitter/rest/request/multipart_with_file'
require 'twitter/rest/response/parse_json'
require 'twitter/rest/response/raise_error'
require 'twitter/rest/utils'

module Twitter
module REST
# Wrapper for the Twitter REST API
#
# @note All methods have been separated into modules and follow the same grouping used in {http://dev.twitter.com/doc the Twitter API Documentation}.
# @see http://dev.twitter.com/pages/every_developer
class Client < Twitter::Client
include Twitter::REST::API
attr_accessor :bearer_token
URL_PREFIX = 'https://api.twitter.com'
ENDPOINT = URL_PREFIX
attr_accessor :bearer_token

# @param connection_options [Hash]
# @return [Hash]
def connection_options=(connection_options)
warn "#{Kernel.caller.first}: [DEPRECATION] Twitter::REST::Client#connection_options= is deprecated and will be removed in version 6.0.0."
warn "#{Kernel.caller.first}: [DEPRECATION] #{self.class.name}##{__method__} is deprecated and will be removed."
@connection_options = connection_options
end

Expand All @@ -48,7 +42,7 @@ def connection_options
# @params middleware [Faraday::RackBuilder]
# @return [Faraday::RackBuilder]
def middleware=(middleware)
warn "#{Kernel.caller.first}: [DEPRECATION] Twitter::REST::Client#middleware= is deprecated and will be removed in version 6.0.0."
warn "#{Kernel.caller.first}: [DEPRECATION] #{self.class.name}##{__method__} is deprecated and will be removed."
@middleware = middleware
end

Expand All @@ -74,15 +68,15 @@ def middleware
end

# Perform an HTTP GET request
def get(path, params = {})
headers = request_headers(:get, URL_PREFIX + path, params)
request(:get, path, params, headers)
def get(path, options = {})
warn "#{Kernel.caller.first}: [DEPRECATION] #{self.class.name}##{__method__} is deprecated. Use Twitter::REST::Request#perform instead."
perform_get(path, options)
end

# Perform an HTTP POST request
def post(path, params = {})
headers = params.values.any? { |value| value.respond_to?(:to_io) } ? request_headers(:post, URL_PREFIX + path, params, {}) : request_headers(:post, URL_PREFIX + path, params)
request(:post, path, params, headers)
def post(path, options = {})
warn "#{Kernel.caller.first}: [DEPRECATION] #{self.class.name}##{__method__} is deprecated. Use Twitter::REST::Request#perform instead."
perform_post(path, options)
end

# @return [Boolean]
Expand All @@ -95,42 +89,34 @@ def credentials?
super || bearer_token?
end

private

# Returns a Faraday::Connection object
#
# @return [Faraday::Connection]
def connection
@connection ||= Faraday.new(URL_PREFIX, connection_options)
end

def request(method, path, params = {}, headers = {})
connection.send(method.to_sym, path, params) { |request| request.headers.update(headers) }.env
rescue Faraday::Error::TimeoutError, Timeout::Error => error
raise(Twitter::Error::RequestTimeout.new(error))
rescue Faraday::Error::ClientError, JSON::ParserError => error
raise(Twitter::Error.new(error))
end

def request_headers(method, url, params = {}, signature_params = params)
bearer_token_request = params.delete(:bearer_token_request)
def request_headers(method, url, options = {}, signature_options = options)
bearer_token_request = options.delete(:bearer_token_request)
headers = {}
if bearer_token_request
headers[:accept] = '*/*'
headers[:authorization] = bearer_token_credentials_auth_header
headers[:content_type] = 'application/x-www-form-urlencoded; charset=UTF-8'
else
headers[:authorization] = auth_header(method, url, params, signature_params)
headers[:authorization] = auth_header(method, url, options, signature_options)
end
headers
end

def auth_header(method, url, params = {}, signature_params = params)
private

def auth_header(method, url, options = {}, signature_options = options)
if !user_token?
@bearer_token = token unless bearer_token?
bearer_auth_header
else
oauth_auth_header(method, url, signature_params).to_s
oauth_auth_header(method, url, signature_options).to_s
end
end

Expand Down
8 changes: 4 additions & 4 deletions lib/twitter/rest/direct_messages.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ module DirectMessages
# @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200.
# @option options [Integer] :page Specifies the page of results to retrieve.
def direct_messages_received(options = {})
get_with_objects('/1.1/direct_messages.json', options, Twitter::DirectMessage)
perform_get_with_objects('/1.1/direct_messages.json', options, Twitter::DirectMessage)
end

# Returns the 20 most recent direct messages sent by the authenticating user
Expand All @@ -41,7 +41,7 @@ def direct_messages_received(options = {})
# @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200.
# @option options [Integer] :page Specifies the page of results to retrieve.
def direct_messages_sent(options = {})
get_with_objects('/1.1/direct_messages/sent.json', options, Twitter::DirectMessage)
perform_get_with_objects('/1.1/direct_messages/sent.json', options, Twitter::DirectMessage)
end

# Returns a direct message
Expand All @@ -56,7 +56,7 @@ def direct_messages_sent(options = {})
# @param options [Hash] A customizable set of options.
def direct_message(id, options = {})
options[:id] = id
get_with_object('/1.1/direct_messages/show.json', options, Twitter::DirectMessage)
perform_get_with_object('/1.1/direct_messages/show.json', options, Twitter::DirectMessage)
end

# @note This method requires an access token with RWD (read, write & direct message) permissions. Consult The Application Permission Model for more information.
Expand Down Expand Up @@ -126,7 +126,7 @@ def destroy_direct_message(*args)
def create_direct_message(user, text, options = {})
merge_user!(options, user)
options[:text] = text
post_with_object('/1.1/direct_messages/new.json', options, Twitter::DirectMessage)
perform_post_with_object('/1.1/direct_messages/new.json', options, Twitter::DirectMessage)
end
alias_method :d, :create_direct_message
alias_method :m, :create_direct_message
Expand Down
6 changes: 3 additions & 3 deletions lib/twitter/rest/favorites.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ module Favorites
def favorites(*args)
arguments = Twitter::Arguments.new(args)
merge_user!(arguments.options, arguments.pop) if arguments.last
get_with_objects('/1.1/favorites/list.json', arguments.options, Twitter::Tweet)
perform_get_with_objects('/1.1/favorites/list.json', arguments.options, Twitter::Tweet)
end

# Un-favorites the specified Tweets as the authenticating user
Expand Down Expand Up @@ -69,7 +69,7 @@ def favorite(*args)
arguments = Twitter::Arguments.new(args)
pmap(arguments) do |tweet|
begin
post_with_object('/1.1/favorites/create.json', arguments.options.merge(:id => extract_id(tweet)), Twitter::Tweet)
perform_post_with_object('/1.1/favorites/create.json', arguments.options.merge(:id => extract_id(tweet)), Twitter::Tweet)
rescue Twitter::Error::AlreadyFavorited, Twitter::Error::NotFound
next
end
Expand All @@ -96,7 +96,7 @@ def favorite(*args)
def favorite!(*args)
arguments = Twitter::Arguments.new(args)
pmap(arguments) do |tweet|
post_with_object('/1.1/favorites/create.json', arguments.options.merge(:id => extract_id(tweet)), Twitter::Tweet)
perform_post_with_object('/1.1/favorites/create.json', arguments.options.merge(:id => extract_id(tweet)), Twitter::Tweet)
end
end
alias_method :create_favorite!, :favorite!
Expand Down
23 changes: 12 additions & 11 deletions lib/twitter/rest/friends_and_followers.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
require 'twitter/arguments'
require 'twitter/cursor'
require 'twitter/relationship'
require 'twitter/rest/request'
require 'twitter/rest/utils'
require 'twitter/user'
require 'twitter/utils'
Expand All @@ -26,7 +27,7 @@ module FriendsAndFollowers
# @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object.
# @param options [Hash] A customizable set of options.
def friend_ids(*args)
cursor_from_response_with_user(:ids, nil, :get, '/1.1/friends/ids.json', args)
cursor_from_response_with_user(:ids, nil, '/1.1/friends/ids.json', args)
end

# @see https://dev.twitter.com/docs/api/1.1/get/followers/ids
Expand All @@ -44,7 +45,7 @@ def friend_ids(*args)
# @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object.
# @param options [Hash] A customizable set of options.
def follower_ids(*args)
cursor_from_response_with_user(:ids, nil, :get, '/1.1/followers/ids.json', args)
cursor_from_response_with_user(:ids, nil, '/1.1/followers/ids.json', args)
end

# Returns the relationship of the authenticating user to the comma separated list of up to 100 screen_names or user_ids provided. Values for connections can be: following, following_requested, followed_by, none.
Expand All @@ -62,7 +63,7 @@ def follower_ids(*args)
def friendships(*args)
arguments = Twitter::Arguments.new(args)
merge_users!(arguments.options, arguments)
get_with_objects('/1.1/friendships/lookup.json', arguments.options, Twitter::User)
perform_get_with_objects('/1.1/friendships/lookup.json', arguments.options, Twitter::User)
end

# Returns an array of numeric IDs for every user who has a pending request to follow the authenticating user
Expand All @@ -74,7 +75,7 @@ def friendships(*args)
# @return [Twitter::Cursor]
# @param options [Hash] A customizable set of options.
def friendships_incoming(options = {})
get_with_cursor('/1.1/friendships/incoming.json', options, :ids)
perform_get_with_cursor('/1.1/friendships/incoming.json', options, :ids)
end

# Returns an array of numeric IDs for every protected user for whom the authenticating user has a pending follow request
Expand All @@ -86,7 +87,7 @@ def friendships_incoming(options = {})
# @return [Twitter::Cursor]
# @param options [Hash] A customizable set of options.
def friendships_outgoing(options = {})
get_with_cursor('/1.1/friendships/outgoing.json', options, :ids)
perform_get_with_cursor('/1.1/friendships/outgoing.json', options, :ids)
end

# Allows the authenticating user to follow the specified users, unless they are already followed
Expand Down Expand Up @@ -131,7 +132,7 @@ def follow(*args)
def follow!(*args)
arguments = Twitter::Arguments.new(args)
pmap(arguments) do |user|
post_with_object('/1.1/friendships/create.json', merge_user(arguments.options, user), Twitter::User)
perform_post_with_object('/1.1/friendships/create.json', merge_user(arguments.options, user), Twitter::User)
end.compact
end
alias_method :create_friendship!, :follow!
Expand Down Expand Up @@ -168,7 +169,7 @@ def unfollow(*args)
# @option options [Boolean] :retweets Enable/disable retweets from the target user.
def friendship_update(user, options = {})
merge_user!(options, user)
post_with_object('/1.1/friendships/update.json', options, Twitter::Relationship)
perform_post_with_object('/1.1/friendships/update.json', options, Twitter::Relationship)
end

# Returns detailed information about the relationship between two users
Expand All @@ -186,7 +187,7 @@ def friendship(source, target, options = {})
options[:source_id] = options.delete(:source_user_id) unless options[:source_user_id].nil?
merge_user!(options, target, 'target')
options[:target_id] = options.delete(:target_user_id) unless options[:target_user_id].nil?
get_with_object('/1.1/friendships/show.json', options, Twitter::Relationship)
perform_get_with_object('/1.1/friendships/show.json', options, Twitter::Relationship)
end
alias_method :friendship_show, :friendship
alias_method :relationship, :friendship
Expand Down Expand Up @@ -226,7 +227,7 @@ def friendship?(source, target, options = {})
# @option options [Boolean, String, Integer] :skip_status Do not include contributee's Tweets when set to true, 't' or 1.
# @option options [Boolean, String, Integer] :include_user_entities The user entities node will be disincluded when set to false.
def followers(*args)
cursor_from_response_with_user(:users, Twitter::User, :get, '/1.1/followers/list.json', args)
cursor_from_response_with_user(:users, Twitter::User, '/1.1/followers/list.json', args)
end

# Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends").
Expand All @@ -250,7 +251,7 @@ def followers(*args)
# @option options [Boolean, String, Integer] :skip_status Do not include contributee's Tweets when set to true, 't' or 1.
# @option options [Boolean, String, Integer] :include_user_entities The user entities node will be disincluded when set to false.
def friends(*args)
cursor_from_response_with_user(:users, Twitter::User, :get, '/1.1/friends/list.json', args)
cursor_from_response_with_user(:users, Twitter::User, '/1.1/friends/list.json', args)
end
alias_method :following, :friends

Expand All @@ -262,7 +263,7 @@ def friends(*args)
# @return [Array<Integer>]
# @param options [Hash] A customizable set of options.
def no_retweet_ids(options = {})
get('/1.1/friendships/no_retweets/ids.json', options).body.collect(&:to_i)
perform_get('/1.1/friendships/no_retweets/ids.json', options).collect(&:to_i)
end
alias_method :no_retweets_ids, :no_retweet_ids
end
Expand Down
Loading

0 comments on commit 65773c7

Please sign in to comment.