Sha256: f21c31eba9d6409ef1d5dc11d0d81a1efe936323f51043d73e575b3197ce85af

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

# frozen_string_literal: true

require 'uri'

module Dribbble
  module Utils
    DEFAULT_ATTRIBUTES = {
      page: 1,
      per_page: 100
    }.freeze

    def class_name
      @class_name ||= is_a?(Class) ? name.split('::').last.downcase : self.class.name.split('::').last.downcase
    end

    def pluralized_class_name
      @pluralized_class_name ||= "#{class_name}s"
    end

    def full_url(path, attrs = {})
      "#{Dribbble::API_URI}#{path}?#{URI.encode_www_form attrs}"
    end

    def full_url_with_default_params(path, attrs = {})
      full_url path, DEFAULT_ATTRIBUTES.merge(attrs)
    end

    def headers
      if @token
        { authorization: "Bearer #{@token}" }
      else
        {}
      end
    end

    def html_get(path, attrs = {})
      res = RestClient.get full_url_with_default_params(path, attrs), headers
      res.force_encoding('UTF-8')
    rescue RestClient::Unauthorized => e
      raise Dribbble::Error::Unauthorized, e
    end

    def html_post(path, attrs = {})
      payload = {}
      yield payload if block_given?
      res = RestClient.post full_url(path, attrs), payload, headers
      res.force_encoding('UTF-8')
    rescue RestClient::Unauthorized => e
      raise Dribbble::Error::Unauthorized, e
    rescue RestClient::UnprocessableEntity => e
      raise Dribbble::Error::Unprocessable, e
    end

    def html_put(path, attrs = {})
      payload = {}
      yield payload if block_given?
      res = RestClient.put full_url(path, attrs), payload, headers
      res.force_encoding('UTF-8')
    rescue RestClient::Unauthorized => e
      raise Dribbble::Error::Unauthorized, e
    rescue RestClient::UnprocessableEntity => e
      raise Dribbble::Error::Unprocessable, e
    end

    def html_delete(path, attrs = {})
      res = RestClient.delete full_url(path, attrs), headers
      res.force_encoding('UTF-8')
    rescue RestClient::Unauthorized => e
      raise Dribbble::Error::Unauthorized, e
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dribbble-2.0.0 lib/dribbble/utils.rb