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.
Instance Method Summary collapse
-
#render_service_error(error) ⇒ void
Renders a service error as a JSON response.
-
#run_service(klass, params) ⇒ Servus::Support::Response?
Executes a service and handles success/failure automatically.
-
#run_service!(klass, **params) ⇒ Servus::Support::DataObject, Object
Executes a service and returns its data on success, raising the failure’s error otherwise.
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.
109 110 111 |
# File 'lib/servus/helpers/controller_helpers.rb', line 109 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.
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 |
#run_service!(klass, **params) ⇒ Servus::Support::DataObject, Object
Executes a service and returns its data on success, raising the failure’s error otherwise.
The bang counterpart to #run_service. Use it outside a standard controller render flow — inside background logic, callbacks, or any place where a failure should propagate as an exception rather than be rendered as JSON.
Inside a service’s ‘#call` method, use Base#call! instead —it preserves the failure Response for the outer service’s caller rather than raising.
Mirrors #run_service: stores the full Response in @result so views and downstream helpers can reach for it the same way, then returns the data on success or raises on failure. The only behavioural difference between the two is raise-vs-render on failure.
Sugar over:
@result = Service.call(**params)
raise @result.error unless @result.success?
data = @result.data
75 76 77 78 79 80 |
# File 'lib/servus/helpers/controller_helpers.rb', line 75 def run_service!(klass, **params) @result = klass.call(**params) return @result.data if @result.success? raise @result.error end |