Sha256: 8e93459419596624695badc731f7d8537065b45dbff97e0faddd9899d8afb0f9

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

class ApiClient::Base
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

  def self.get(url = '')
    call do Net::HTTP.get_response(URI.parse(url)) end
  end

  def self.post(url = '', args = {})
    call do Net::HTTP.post_form(URI.parse(url), args) end
  end

  protected

  def self.call
    begin
      response = yield
    rescue Errno::ECONNREFUSED
      raise ApiClient::Exceptions::ConnectionRefused
    end
    raise_exception(response.code)
    new(JSON.parse(response.body))
  end

  def self.raise_exception(code)
    case code
      when '401' then raise ApiClient::Exceptions::Unauthorized
      when '403' then raise ApiClient::Exceptions::Forbidden
      when '404' then raise ApiClient::Exceptions::NotFound
      when '500' then raise ApiClient::Exceptions::InternalServerError
      when '502' then raise ApiClient::Exceptions::BadGateway
      when '503' then raise ApiClient::Exceptions::ServiceUnavailable
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
api-client-1.0.0 lib/api-client/base.rb