Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 80 lines (67 sloc) 2.105 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
require 'faraday'
require 'simple_oauth'
require 'twitter/core_ext/hash'
require 'uri'

module Twitter
  # Defines HTTP request methods
  module Requestable

    # Perform an HTTP DELETE request
    def delete(path, params={}, options={})
      request(:delete, path, params, options)
    end

    # Perform an HTTP GET request
    def get(path, params={}, options={})
      request(:get, path, params, options)
    end

    # Perform an HTTP POST request
    def post(path, params={}, options={})
      request(:post, path, params, options)
    end

  private

    # Returns a Faraday::Connection object
    #
    # @return [Faraday::Connection]
    def connection
      return @connection if defined? @connection

      default_options = {
        :headers => {
          :accept => 'application/json',
          :user_agent => user_agent,
        },
        :proxy => proxy,
        :ssl => {:verify => false},
      }

      options = default_options.deep_merge(connection_options)

      @connection = Faraday.new(endpoint, options.merge(:builder => middleware))
    end

    # Perform an HTTP request
    def request(method, path, params, options)
      uri = options[:endpoint] || endpoint
      uri = URI(uri) unless uri.respond_to?(:host)
      uri += path
      headers = {}
      if credentials?
        signature_params = params
        params.values.each do |value|
          signature_params = {} if value.is_a?(Hash)
        end
        header = SimpleOAuth::Header.new(method, uri, signature_params, credentials)
        headers['Authorization'] = header.to_s
      end

      response = connection.run_request(method.to_sym, path, nil, headers) do |request|
        request.options[:raw] = true if options[:raw]
        unless params.empty?
          if :post == request.method
            request.body = params
          else
            request.params.update params
          end
        end
        yield request if block_given?
      end

      options[:raw] ? response : response.body
    rescue Faraday::Error::ClientError
      raise Twitter::Error::ClientError
    end

  end
end
Something went wrong with that request. Please try again.