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
-
#respond_with_error(error = nil, status: :unprocessable_entity, options: {}) ⇒ Object
Respond with an error response.
-
#respond_with_pagination(collection, options = {}) ⇒ Object
Respond with a paginated collection.
-
#respond_with_success(data = nil, status: :ok, options: {}) ⇒ Object
Respond with a success response.
Instance Method Details
#respond_with_error(error = nil, status: :unprocessable_entity, options: {}) ⇒ Object
Respond with an 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.is_a?(Exception) ? error. : error.to_s error_type = error.is_a?(Exception) ? error.class.name : 'Error' response = { success: false, error: { type: error_type, message: , }, }.merge() if defined?(render) render json: response, status: status else response end end |
#respond_with_pagination(collection, options = {}) ⇒ Object
Respond with a paginated collection
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, = {}) page = ([:page] || 1).to_i per_page = ([: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
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() if defined?(render) render json: response, status: status else response end end |