Class: Elements::APIResource

Inherits:
ElementsObject show all
Defined in:
lib/elements/resources/api_resource.rb

Overview

All API resources, such as Charges, Refunds, are defined under lib/elements/resources.

Each API resource should have an OBJECT_NAME, corresponding to the “type” in a JSON response of that resource.

API endpoints are defined with ‘api_method`, e.g.,

class MyAPIResource < APIResource

api_method :create, method: :post, path: '/api/v1/my_api_resource'

end

To break it down:

  • ‘:create` defines the name of the class method that invokes the API request

  • ‘method: :post` defines the HTTP verb that is associated with this endpoint

  • ‘path: ’/api/v1/my_api_resource’‘ defines the API path

To invoke this API method:

params =

foo: "bar"

headers =

MyHeaderVar: "value"

my_api_resource = MyAPIResource.create(params, headers)

Here, ‘params` are the API params that will be encoded automatically according to the HTTP verb. You may also supply optional headers, common headers such as `Idempotency-Key` will be supplied with a default.

Constant Summary

Constants inherited from ElementsObject

ElementsObject::PERMANENT_ATTRIBUTES, ElementsObject::RESERVED_FIELD_NAMES

Class Method Summary collapse

Methods inherited from ElementsObject

#[], #as_json, #initialize, #to_json

Constructor Details

This class inherits a constructor from Elements::ElementsObject

Class Method Details

.api_method(name, method:, path:, parser: nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/elements/resources/api_resource.rb', line 41

def api_method(name, method:, path:, parser: nil)
  unless %i[get post delete].include?(method)
    raise ArgumentError,
          "Invalid method value: #{method.inspect}. Should be one " \
          'of :get, :post or :delete.'
  end

  url_template = Addressable::Template.new(path)
  if url_template.variables.include?('id')
    define_resource_method(name, method, path, parser)
  else
    define_api_method(name, method, path, parser)
  end
end

.execute_resource_request(method, url, params = {}, headers = {}, opts = {}) ⇒ Object



34
35
36
37
38
39
# File 'lib/elements/resources/api_resource.rb', line 34

def execute_resource_request(method, url, params = {}, headers = {}, opts = {})
  client = opts[:client] || ElementsClient.active_client

  client.execute_request(method, url,
                         params: params, headers: headers, opts: opts)
end