Module: Forem::APIOperations::Create

Overview

Adds a create class method to any resource that extends this module.

Sends a POST request to the resource's collection path with the supplied parameters as a JSON body, and returns a new resource instance populated from the API response.

Examples:

Extending a resource class

class Forem::Article < Forem::APIResource
  extend APIOperations::Create
end

Instance Method Summary collapse

Instance Method Details

#create(params = {}, opts = {}) ⇒ ForemObject

Create a new resource via the Forem API.

Sends a POST request to Forem::APIResource.resource_path with params serialised as a JSON body. The server response is used to construct and return a new resource instance.

Examples:

Creating an article

article = client.articles.create(
  article: { title: "Hello, world!", body_markdown: "**hi**", published: true }
)
article.id     #=> 12345
article.title  #=> "Hello, world!"

Parameters:

  • params (Hash) (defaults to: {})

    the attributes for the new resource (e.g. { article: { title: "Hello", body_markdown: "..." } }).

  • opts (Hash) (defaults to: {})

    per-request options.

Options Hash (opts):

  • :api_key (String)

    override the API key for this request.

  • :requestor (APIRequestor)

    a custom requestor to use.

Returns:

  • (ForemObject)

    the newly-created resource, constructed from the API response body.

Raises:

See Also:



40
41
42
43
44
# File 'lib/forem/api_operations/create.rb', line 40

def create(params = {}, opts = {})
  requestor = opts[:requestor]
  resp = request(:post, resource_path, params, opts)
  construct_from(resp.parsed_body, requestor: requestor)
end