Module: BetterController::ResponseHelpers

Extended by:
ActiveSupport::Concern
Defined in:
lib/better_controller/response_helpers.rb

Overview

Module providing helper methods for standardized API responses

Instance Method Summary collapse

Instance Method Details

#respond_with_error(error = nil, status: :unprocessable_entity, options: {}) ⇒ Object

Respond with an error response

Parameters:

  • error (Exception, String) (defaults to: nil)

    The error or error message

  • status (Symbol, Integer) (defaults to: :unprocessable_entity)

    The HTTP status code

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

    Additional options for the response

Returns:

  • (Object)

    The formatted error response



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/better_controller/response_helpers.rb', line 31

def respond_with_error(error = nil, status: :unprocessable_entity, options: {})
  error_message = error.is_a?(Exception) ? error.message : error.to_s
  error_type    = error.is_a?(Exception) ? error.class.name : 'Error'

  response = {
    success: false,
    error:   {
      type:    error_type,
      message: error_message,
    },
  }.merge(options)

  if defined?(render)
    render json: response, status: status
  else
    response
  end
end

#respond_with_pagination(collection, options = {}) ⇒ Object

Respond with a paginated collection

Parameters:

  • collection (Object)

    The collection to paginate

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

    Pagination options

Returns:

  • (Object)

    The paginated response



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/better_controller/response_helpers.rb', line 54

def respond_with_pagination(collection, options = {})
  page     = (options[:page] || 1).to_i
  per_page = (options[:per_page] || 25).to_i

  paginated = collection.page(page).per(per_page)

  respond_with_success(
    paginated,
    options: {
      meta: {
        pagination: {
          current_page: paginated.current_page,
          total_pages:  paginated.total_pages,
          total_count:  paginated.total_count,
        },
      },
    }
  )
end

#respond_with_success(data = nil, status: :ok, options: {}) ⇒ Object

Respond with a success response

Parameters:

  • data (Object) (defaults to: nil)

    The data to include in the response

  • status (Symbol, Integer) (defaults to: :ok)

    The HTTP status code

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

    Additional options for the response

Returns:

  • (Object)

    The formatted response



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/better_controller/response_helpers.rb', line 13

def respond_with_success(data = nil, status: :ok, options: {})
  response = {
    success: true,
    data:    data,
  }.merge(options)

  if defined?(render)
    render json: response, status: status
  else
    response
  end
end