Sha256: 441eac9cb57b3545bab09e77b92cbba45f07af3969d7fa5252262ca58b502537

Contents?: true

Size: 1.64 KB

Versions: 1

Compression:

Stored size: 1.64 KB

Contents

require 'faraday'
require 'multi_json'

module Credly
  module Connection

    def new_connection
      default_options = {
        :headers => {
          :accept       => 'application/json',
          :content_type => 'application/x-www-form-urlencoded',
          :user_agent   => Credly.user_agent,
        }
      }
      Faraday.new(self.base_url, default_options) do |builder|
        builder.use Credly::Response::FollowRedirects
        builder.request :multipart
        builder.request :url_encoded
        # builder.use Faraday::Request::Multipart
        # builder.use Faraday::Request::UrlEncoded

        builder.response :logger, ::Logger.new(STDOUT), :bodies => true if Credly.debugging?
        builder.adapter Faraday.default_adapter
      end
    end

    def connection
      @connection ||= new_connection
    end

    def get(path, params = Hash.new, headers = Hash.new)
      request(:get, path, params, headers)
    end

    def post(path, params = Hash.new, headers = Hash.new)
      request(:post, path, params, headers)
    end

    def put(path, params = Hash.new, headers = Hash.new)
      request(:put, path, params, headers)
    end

    def delete(path, params = Hash.new, headers = Hash.new)
      request(:delete, path, params, headers)
    end

    def request(method, path, params, headers)
      response = connection.send(method) do |request|
        case method.to_sym
        when :delete, :get
          request.url(path, params)
        when :post, :put
          request.path = path
          request.body = params unless params.empty?
        end
        request.headers.merge!(headers)
      end
      response.body
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
credly-0.0.1 lib/credly/connection.rb