Class: Servus::Support::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/servus/support/response.rb

Overview

Encapsulates the result of a service execution.

Response objects are returned by all service calls and contain either successful data or an error, never both. Use #success? to determine which path to take when handling results.

Examples:

Handling a successful response

result = MyService.call(user_id: 123)
if result.success?
  puts "Data: #{result.data}"
  puts "Error: #{result.error}" # => nil
end

Handling a failed response

result = MyService.call(user_id: -1)
unless result.success?
  puts "Error: #{result.error.message}"
  puts "Data: #{result.data}" # => nil
end

Pattern matching in controllers

result = MyService.call(params)
if result.success?
  render json: result.data, status: :ok
else
  render json: result.error.message, status: :unprocessable_entity
end

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(success, data, error) ⇒ Response

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Note:

This is typically called by Base#success or Base#failure rather than being instantiated directly.

Creates a new response object.

Parameters:

  • success (Boolean)

    true for successful responses, false for failures

  • data (Object, nil)

    the result data (nil for failures)

  • error (Servus::Support::Errors::ServiceError, nil)

    the error (nil for successes)



52
53
54
55
56
# File 'lib/servus/support/response.rb', line 52

def initialize(success, data, error)
  @success = success
  @data = data
  @error = error
end

Instance Attribute Details

#dataObject (readonly)

[Object] The data returned by the service



37
38
39
# File 'lib/servus/support/response.rb', line 37

def data
  @data
end

#errorObject (readonly)

[Servus::Support::Errors::ServiceError] The error returned by the service



40
41
42
# File 'lib/servus/support/response.rb', line 40

def error
  @error
end

Instance Method Details

#success?Boolean

Checks if the service execution was successful.

Examples:

result = MyService.call(params)
if result.success?
  # Handle success - result.data is available
else
  # Handle failure - result.error is available
end

Returns:

  • (Boolean)

    true if the service succeeded, false if it failed



69
70
71
# File 'lib/servus/support/response.rb', line 69

def success?
  @success
end