Sha256: b31c747b4d187100390cd04799eb4edd38fe7c9dff42eb4799da5a6faff9b971

Contents?: true

Size: 1.3 KB

Versions: 10

Compression:

Stored size: 1.3 KB

Contents

require "uri"
require "net/http"

module Pushpad
  module Request
    extend self

    def head(endpoint, options = {})
      perform(Net::HTTP::Head, endpoint, options)
    end

    def get(endpoint, options = {})
      perform(Net::HTTP::Get, endpoint, options)
    end

    def post(endpoint, body, options = {})
      perform(Net::HTTP::Post, endpoint, options) do |request|
        request.body = body
      end
    end

    private

    def perform(method, endpoint, options)
      uri = URI.parse(endpoint)
      request = method.new(path_and_query(uri, options[:query_parameters]), headers)

      yield request if block_given?

      https(uri, request)
    end

    def path_and_query(uri, query_parameters)
      [uri.path, query(query_parameters)].compact.join("?")
    end

    def query(parameters)
      parameters && !parameters.empty? ? URI.encode_www_form(parameters) : nil
    end

    def https(uri, request)
      Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |https|
        https.request(request)
      end
    end

    def headers
      raise "You must set Pushpad.auth_token" unless Pushpad.auth_token
      {
        "Authorization" => %(Token token="#{Pushpad.auth_token}"),
        "Content-Type" => "application/json;charset=UTF-8",
        "Accept" => "application/json"
      }
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
pushpad-1.0.0 lib/pushpad/request.rb
pushpad-0.13.0 lib/pushpad/request.rb
pushpad-0.12.0 lib/pushpad/request.rb
pushpad-0.11.1 lib/pushpad/request.rb
pushpad-0.11.0 lib/pushpad/request.rb
pushpad-0.10.0 lib/pushpad/request.rb
pushpad-0.9.0 lib/pushpad/request.rb
pushpad-0.8.0 lib/pushpad/request.rb
pushpad-0.7.0 lib/pushpad/request.rb
pushpad-0.6.0 lib/pushpad/request.rb