class Billplz::Model

Attributes

api_url[RW]
endpoint[W]
payload[RW]
response[RW]

Public Class Methods

new(payload={}) click to toggle source
# File lib/billplz/model.rb, line 7
def initialize(payload={})
  @api_url  = self.api_url
  @payload  = payload
end

Public Instance Methods

api_url() click to toggle source
# File lib/billplz/model.rb, line 43
def api_url
  self.class.api_url
end
endpoint() click to toggle source
# File lib/billplz/model.rb, line 47
def endpoint
  URI.parse(@api_url)
end
parsed_json() click to toggle source
# File lib/billplz/model.rb, line 55
def parsed_json
  JSON.parse(@response.body)
end
request(method, body) click to toggle source
# File lib/billplz/model.rb, line 12
def request(method, body)
  headers = {
    "Authorization" => "Basic " + Base64.encode64(Billplz.configuration.api_key + ":").strip,
    "Content-Type"  => "application/json",
    "Accept"        => "application/json"
  }

  @response = case method
  when :get
    raise ArgumentError, "GET requests do not support a request body" if body
    http.get(endpoint.request_uri, headers)
  when :post
    http.post(endpoint.request_uri, body.to_json, headers)
  when :put
    http.put(endpoint.request_uri, body.to_json, headers)
  when :patch
    http.patch(endpoint.request_uri, body, headers)
  when :delete
    raise ArgumentError, "DELETE requests do not support a request body" if body
    http.delete(endpoint.request_uri, headers)
  else
    raise ArgumentError, "Unsupported request method #{method.to_s.upcase}"
  end

  @response
end
success?() click to toggle source
# File lib/billplz/model.rb, line 51
def success?
  @response.is_a?(Net::HTTPOK)
end

Private Instance Methods

http() click to toggle source
# File lib/billplz/model.rb, line 61
def http
  http = Net::HTTP.new(endpoint.host, endpoint.port)
  http.use_ssl = true
  http.open_timeout = Billplz.configuration.http_timeout
  http.read_timeout = Billplz.configuration.http_timeout
  # http.set_debug_output($stdout)
  http
end
requires!(hash, *params) click to toggle source
# File lib/billplz/model.rb, line 70
def requires!(hash, *params)
  params.each do |param|
    if param.is_a?(Array)
      raise ArgumentError.new("Missing required parameter: #{param.first}") unless hash.has_key?(param.first)

      valid_options = param[1..-1]
      raise ArgumentError.new("Parameter: #{param.first} must be one of #{valid_options.to_sentence(:words_connector => 'or')}") unless valid_options.include?(hash[param.first])
    else
      raise ArgumentError.new("Missing required parameter: #{param}") unless hash.has_key?(param)
    end
  end
end