Module: Railsmith::ControllerHelpers

Extended by:
ActiveSupport::Concern
Defined in:
lib/railsmith/controller_helpers.rb

Overview

Include this concern in an ApplicationController (or a specific controller) to get automatic JSON error responses when a service raises Failure.

Examples:

class ApplicationController < ActionController::API
  include Railsmith::ControllerHelpers
end

# In an action:
UserService.call!(action: :create, params: ..., context: ...)
# => on failure, renders JSON with the right HTTP status automatically

Constant Summary collapse

ERROR_STATUS_MAP =

Maps Railsmith error codes to HTTP status symbols understood by Rails’ render json:, status:.

{
  "validation_error" => :unprocessable_entity,
  "not_found" => :not_found,
  "conflict" => :conflict,
  "unauthorized" => :unauthorized,
  "unexpected" => :internal_server_error
}.freeze

Instance Method Summary collapse

Instance Method Details

#railsmith_context(domain: nil, **extras) ⇒ Railsmith::Context

Builds a Railsmith::Context seeded with the incoming request’s id, so every service invoked from this controller shares the same request_id as the X-Request-Id header ActionDispatch observed.

Examples:

Propagating the request id into a service call

class OrdersController < ApplicationController
  include Railsmith::ControllerHelpers

  def create
    result = OrderService.call!(
      action: :create,
      params: { attributes: order_params },
      context: railsmith_context(domain: :commerce, actor_id: current_user.id)
    )
    render json: result.value, status: :created
  end
end

Parameters:

  • domain (Symbol, String, nil) (defaults to: nil)

    bounded-context key for the call

  • extras (Hash)

    arbitrary extra keys (actor_id, tenant_id, etc.)

Returns:



65
66
67
68
69
70
71
72
73
74
# File 'lib/railsmith/controller_helpers.rb', line 65

def railsmith_context(domain: nil, **extras)
  request_id = extras.delete(:request_id)
  request_id ||= request.request_id if respond_to?(:request) && request.respond_to?(:request_id)

  Railsmith::Context.new(
    domain: domain,
    request_id: request_id,
    **extras
  )
end