What is a result?

  • A result is the data structure every Convenient Service service returns. It is inspired by JSend, but not JSend-compatible. It provides a unified way to check the outcome of an operation and access its data, message, and code.

    class FindUser
      include ConvenientService::Standard::Config
    
      attr_reader :id
    
      def initialize(id:)
        @id = id
      end
    
      def result
        return error("Id is `nil`") if id.nil?
    
        users = {1 => {name: "John"}}
    
        return failure("User with id `#{id}` does not exist") unless users.key?(id)
    
        success(user: users[id])
      end
    end
    
    result = FindUser.result(id: 1)
    
    result.class
    # => FindUser::Result
    
    result.status.to_sym
    # => :success
  • Status checks: success?, failure?, error?, not_success?, not_failure?, not_error?.

  • Attributes: status, data, message, code, service (the service instance that produced the result), original_service (for results returned via steps, the step's own service - not the organizer).

    result.success?
    # => true
    
    result.data[:user]
    # => {name: "John"}
  • Accessing data, message, or code before checking the result's status raises an error.

    result = FindUser.result(id: 1)
    
    result.data
    # raises ConvenientService::Service::Plugins::HasJSendResult::Entities::Result::Plugins::RaisesOnNotCheckedResultStatus::Exceptions::StatusIsNotChecked
  • ud, um, and uc are debugger-friendly shortcuts for unsafe_data, unsafe_message, and unsafe_code - they skip the status check, which is convenient when inspecting a result in a debugger session.

    result.ud
    # => <FindUser::Result::Data user: {name: "John"}>

See also

Sources