Module: Showroom::Core::Connection

Included in:
Showroom::Client
Defined in:
lib/showroom/core/connection.rb

Overview

Mixin that provides HTTP connectivity via Faraday.

Expects the including class to expose configuration keys from Configurable: store, user_agent, open_timeout, timeout, middleware, and connection_options.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#last_responseFaraday::Response? (readonly)

Returns the last HTTP response object.

Returns:

  • (Faraday::Response, nil)

    the last HTTP response object



14
15
16
# File 'lib/showroom/core/connection.rb', line 14

def last_response
  @last_response
end

Instance Method Details

#agentFaraday::Connection

Memoized Faraday connection built from the current configuration.

Returns:

  • (Faraday::Connection)


26
27
28
# File 'lib/showroom/core/connection.rb', line 26

def agent
  @agent ||= build_agent
end

#base_urlString

Returns the canonical HTTPS base URL for the configured store.

Returns:

  • (String)


19
20
21
# File 'lib/showroom/core/connection.rb', line 19

def base_url
  StoreUrl.resolve(store)
end

#get(path, params = {}) ⇒ Object

Performs a GET request and returns the parsed response body.

Parameters:

  • path (String)

    path relative to the store base URL

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

    query parameters

Returns:

  • (Object)

    parsed JSON body (Hash or Array)



35
36
37
38
39
# File 'lib/showroom/core/connection.rb', line 35

def get(path, params = {})
  puts "GET #{path} with params #{params}" if Showroom.debug
  @last_response = agent.get(path, params)
  @last_response.body
end

#paginate(path, key, params = {}, max_pages: pagination_depth) {|items, page| ... } ⇒ void

This method returns an undefined value.

Iterates through paginated responses, yielding each page of items.

Stops when a page returns an empty array or pagination_depth is reached.

Parameters:

  • path (String)

    path relative to the store base URL

  • key (String)

    top-level JSON key containing the items array

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

    base query parameters (page/limit are added automatically)

Yields:

  • (items, page)

    items on the current page and the page number

Yield Parameters:

  • items (Array)

    the deserialized items for this page

  • page (Integer)

    1-based page number



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/showroom/core/connection.rb', line 53

def paginate(path, key, params = {}, max_pages: pagination_depth, &blk)
  page_limit = per_page

  (1..max_pages).each do |page|
    paged_params = params.merge(limit: page_limit, page: page)
    body         = get(path, paged_params)
    items        = body.is_a?(Hash) ? body[key] || body[key.to_s] : body

    break if items.nil? || items.empty?

    blk.call(items, page)
  end
end