Class: Respondo::ResponseBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/respondo/response_builder.rb

Overview

Builds the standardized response hash.

Every response always contains these top-level keys:

{
  success: Boolean,
  message: String,
  data:    Object | Array | nil,
  meta:    Hash
}

The meta block always contains:

{ timestamp: ISO8601 String }

Plus pagination keys when pagination: true and the data is a paginated collection. Plus request_id when config.include_request_id is true. Plus pagination when a pagination hash is supplied by the caller.

Instance Method Summary collapse

Constructor Details

#initialize(success:, data: nil, message: nil, meta: {}, errors: nil, pagination: nil, request: nil) ⇒ ResponseBuilder

Returns a new instance of ResponseBuilder.

Parameters:

  • success (Boolean)
  • data (Object) (defaults to: nil)

    anything — serialized automatically

  • message (String) (defaults to: nil)
  • meta (Hash) (defaults to: {})

    caller-supplied extra meta (merged in)

  • errors (Hash) (defaults to: nil)

    field-level errors (for 422 responses)

  • pagination (Hash, nil) (defaults to: nil)

    plain pagination hash supplied by the caller, e.g. { current_page: 1, per_page: 25, total_pages: 4,

    total_count: 100, next_page: 2, prev_page: nil }
    
  • request (Object) (defaults to: nil)

    ActionDispatch::Request (for request_id)



31
32
33
34
35
36
37
38
39
40
# File 'lib/respondo/response_builder.rb', line 31

def initialize(success:, data: nil, message: nil, meta: {}, errors: nil,
               pagination: nil, request: nil)
  @success    = success
  @raw_data   = data
  @message    = message
  @extra_meta = meta || {}
  @errors     = errors
  @pagination = pagination
  @request    = request
end

Instance Method Details

#buildHash

Returns the complete response payload.

Returns:

  • (Hash)

    the complete response payload



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/respondo/response_builder.rb', line 43

def build
  # We initialize the hash in the exact order we want keys to appear
  payload = {
    success: @success,
    message: resolve_message,
    data:    serialize_data,
  }

  # Add errors before meta if they exist
  payload[:errors] = @errors if @errors && !@errors.empty?

  # Finally, add meta so it appears at the bottom
  payload[:meta] = build_meta

  apply_camelize(payload)
end