Module: Forem::APIOperations::List

Overview

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

Fetches a paginated collection from the resource's path and wraps the result in a ListObject that supports manual and automatic pagination.

Examples:

Extending a resource class

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

Instance Method Summary collapse

Instance Method Details

#list(params = {}, opts = {}) ⇒ ListObject

Retrieve a paginated list of resources from the Forem API.

Sends a GET request to Forem::APIResource.resource_path with params appended as query-string parameters. The response array is converted into an array of resource instances and wrapped in a ListObject that exposes pagination helpers.

Pagination defaults: page 1, per_page 30 (matching Forem API defaults). These can be overridden via params.

Examples:

Fetching the first page of articles

articles = client.articles.list(per_page: 10)
articles.map(&:title)
#=> ["Article 1", "Article 2", ...]

Filtering articles by tag

client.articles.list(tag: "ruby", per_page: 5).each do |a|
  puts a.title
end

Parameters:

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

    query parameters for filtering and pagination.

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

    per-request options.

Options Hash (params):

  • :page (Integer)

    the page number to fetch (default 1).

  • :per_page (Integer)

    the number of items per page (default 30, maximum varies by endpoint).

  • :tag (String)

    filter articles by tag (articles endpoint).

  • :username (String)

    filter by username.

  • :state (String)

    filter by state (e.g. "fresh", "rising", "all").

Options Hash (opts):

  • :api_key (String)

    override the API key for this request.

  • :requestor (APIRequestor)

    a custom requestor to use and to forward to subsequent page fetches.

Returns:

  • (ListObject)

    a paginated list object wrapping the current page's resources.

Raises:

See Also:



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/forem/api_operations/list.rb', line 52

def list(params = {}, opts = {})
  requestor = opts[:requestor]
  resp = request(:get, resource_path, params, opts)
  data = (resp.parsed_body || []).map { |item| construct_from(item, requestor: requestor) }
  per_page = params[:per_page] || params["per_page"] || 30
  page = params[:page] || params["page"] || 1

  ListObject.new(
    data: data,
    current_page: page.to_i,
    per_page: per_page.to_i,
    resource_class: self,
    filters: params.reject { |k, _| [:page, :per_page, "page", "per_page"].include?(k) },
    requestor: requestor
  )
end