Sha256: 41bec117df6de983ad12dacb2281561181b34d8fb9a10ff3040233bb17559d30

Contents?: true

Size: 1012 Bytes

Versions: 6

Compression:

Stored size: 1012 Bytes

Contents

require 'httparty'

module Watchdocs
  module Rails
    module Bridge
      class WatchdocsApiError < StandardError; end

      DEFAULT_ERROR = 'Unknown API Error occured.'.freeze

      class << self
        def send(payload)
          response = HTTParty.post(
            api_url,
            body: payload.to_json,
            headers: { 'Content-Type' => 'application/json' }
          )
          check_response(response)
        end

        private

        def check_response(response)
          case response.code.to_s.chars.first
          when '2'
            true
          when '4', '5'
            raise WatchdocsApiError, get_error(response.body)
          else
            raise WatchdocsApiError, DEFAULT_ERROR
          end
        end

        def get_error(response_body)
          JSON.parse(response_body)['errors'].join(', ')
        rescue
          DEFAULT_ERROR
        end

        def api_url
          Watchdocs::Rails.configuration.sync_url
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
watchdocs-rails-0.2.0 lib/watchdocs/rails/bridge.rb
watchdocs-rails-0.1.4 lib/watchdocs/rails/bridge.rb
watchdocs-rails-0.1.3 lib/watchdocs/rails/bridge.rb
watchdocs-rails-0.1.2 lib/watchdocs/rails/bridge.rb
watchdocs-rails-0.1.1 lib/watchdocs/rails/bridge.rb
watchdocs-rails-0.1.0 lib/watchdocs/rails/bridge.rb