Module: Servus::Helpers::ControllerHelpers

Defined in:
lib/servus/helpers/controller_helpers.rb

Overview

Rails controller helper methods for service integration.

Provides convenient methods for calling services from controllers and handling their responses. Automatically included in ActionController::Base when Servus is loaded in a Rails application.

Examples:

Including in a controller

class ApplicationController < ActionController::Base
  include Servus::Helpers::ControllerHelpers
end

See Also:

Instance Method Summary collapse

Instance Method Details

#render_service_error(error) ⇒ void

This method returns an undefined value.

Renders a service error as a JSON response.

Uses error.http_status for the response status code and error.api_error for the response body.

Override this method in your controller to customize error response format.

Examples:

Default behavior

# Renders: { error: { code: :not_found, message: "User not found" } }
# With status: 404

Custom error rendering

def render_service_error(error)
  render json: {
    error: {
      type: error.api_error[:code],
      details: error.message,
      timestamp: Time.current
    }
  }, status: error.http_status
end

Parameters:

See Also:



69
70
71
# File 'lib/servus/helpers/controller_helpers.rb', line 69

def render_service_error(error)
  render json: { error: error.api_error }, status: error.http_status
end

#run_service(klass, params) ⇒ Servus::Support::Response?

Executes a service and handles success/failure automatically.

On success, stores the result in @result for use in views. On failure, renders the error as JSON with the appropriate HTTP status.

Examples:

Basic usage

class UsersController < ApplicationController
  def create
    run_service Services::CreateUser::Service, user_params
  end
end

Parameters:

  • klass (Class)

    service class to execute (must inherit from Base)

  • params (Hash)

    keyword arguments to pass to the service

Returns:

See Also:



37
38
39
40
# File 'lib/servus/helpers/controller_helpers.rb', line 37

def run_service(klass, params)
  @result = klass.call(**params)
  render_service_error(@result.error) unless @result.success?
end