Module: ConcernsOnRails::Controllers::Respondable
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/concerns_on_rails/controllers/respondable.rb
Overview
Standardized JSON envelopes for API controllers.
class Api::ArticlesController < ApplicationController
include ConcernsOnRails::Controllers::Respondable
def show
article = Article.find_by(id: params[:id])
return render_error(message: "Not found", status: :not_found) unless article
render_success(data: article)
end
def create
article = Article.new(article_params)
if article.save
render_success(data: article, status: :created)
else
render_error(message: "Invalid", errors: article.errors.)
end
end
end
Note: ‘data:` is a keyword arg (not positional) to sidestep Ruby 3’s behavior of treating hash literals as kwargs when a method declares any keyword params — this lets callers pass hash data without surprises.
Instance Method Summary collapse
-
#render_error(message:, status: :unprocessable_entity, code: nil, errors: nil) ⇒ Object
Error envelope: { success: false, error: { message:, code?, details? } }.
-
#render_success(data: nil, status: :ok, meta: {}) ⇒ Object
Success envelope: { success: true, data: <data>, meta: <meta> } ‘meta:` is omitted from the JSON when empty so simple responses stay clean.
Instance Method Details
#render_error(message:, status: :unprocessable_entity, code: nil, errors: nil) ⇒ Object
Error envelope:
{ success: false, error: { message:, code?, details? } }
44 45 46 47 48 49 50 |
# File 'lib/concerns_on_rails/controllers/respondable.rb', line 44 def render_error(message:, status: :unprocessable_entity, code: nil, errors: nil) error = { message: } error[:code] = code if code error[:details] = errors if errors render json: { success: false, error: error }, status: status end |
#render_success(data: nil, status: :ok, meta: {}) ⇒ Object
Success envelope:
{ success: true, data: <data>, meta: <meta> }
‘meta:` is omitted from the JSON when empty so simple responses stay clean.
36 37 38 39 40 |
# File 'lib/concerns_on_rails/controllers/respondable.rb', line 36 def render_success(data: nil, status: :ok, meta: {}) body = { success: true, data: data } body[:meta] = if .is_a?(Hash) && .any? render json: body, status: status end |