Sha256: 3d7bd85e6306e2d001609ed527b31f8b225c617e10b6034462d6fcd8ec87de59

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

module Locomotive::Coal

  module Request

    def get(endpoint, parameters = {}, raw = false)
      safe_request_call(raw) do
        Unirest.get   "#{uri.to_s}/#{endpoint}.json",
          headers:    { 'Accept' => 'application/json' },
          auth:       uri.userinfo,
          parameters: parameters.merge(auth_token: token)
      end
    end

    def post(endpoint, parameters = {})
      parameters = parameters.merge(auth_token: token) if respond_to?(:token)

      safe_request_call do
        Unirest.post  "#{uri.to_s}/#{endpoint}.json",
          auth:       uri.userinfo,
          headers:    { 'Accept' => 'application/json' },
          parameters: parameters
      end
    end

    def put(endpoint, parameters = {})
      parameters = parameters.merge(auth_token: token) if respond_to?(:token)

      safe_request_call do
        Unirest.put   "#{uri.to_s}/#{endpoint}.json",
          auth:       uri.userinfo,
          headers:    { 'Accept' => 'application/json' },
          parameters: parameters
      end
    end

    def delete(endpoint, id)
      safe_request_call do
        Unirest.delete    "#{uri.to_s}/#{endpoint}/#{id}.json",
          auth:           uri.userinfo,
          headers:        { 'Accept' => 'application/json' },
          parameters:     { auth_token: token }
      end
    end

    private

    def safe_request_call(raw = false, &block)
      response = begin
        yield
      rescue Exception => e
        raise Locomotive::Coal::BadRequestError.new(e)
      end

      if response.code == 200
        raw ? response : response.body
      else
        raise Locomotive::Coal::Error.from_response(response)
      end
    end

  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
locomotivecms_coal-1.0.0.pre.alpha.1 lib/locomotive/coal/request.rb
locomotivecms_coal-1.0.0.pre.alpha lib/locomotive/coal/request.rb