Class: FService::Result::Failure

Inherits:
Base
  • Object
show all
Defined in:
lib/f_service/result/failure.rb

Overview

Represents a value of a failed operation. The error field can contain any information you want.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#on

Constructor Details

#initialize(error) ⇒ Failure

Creates a failed operation. You usually shouldn’t call this directly. See Base#failure.

Parameters:

  • error (Object)

    failure value.



20
21
22
23
# File 'lib/f_service/result/failure.rb', line 20

def initialize(error)
  @error = error
  freeze
end

Instance Attribute Details

#errorObject (readonly)

Returns the provided error



14
15
16
# File 'lib/f_service/result/failure.rb', line 14

def error
  @error
end

Instance Method Details

#failed?Boolean

Returns true.

Examples:

# Suppose that User::Update returns an FService::Result

log_errors(user) if User::Update.(user: user).failed?

Returns:

  • (Boolean)


43
44
45
# File 'lib/f_service/result/failure.rb', line 43

def failed?
  true
end

#successful?Boolean

Returns false.

Examples:

# Suppose that User::Update returns an FService::Result

log_errors(user) unless User::Update.(user: user).successful?

Returns:

  • (Boolean)


32
33
34
# File 'lib/f_service/result/failure.rb', line 32

def successful?
  false
end

#thenself

Returns itself to the given block. Use this to chain multiple service calls (since all services return Results). It will short circuit your service call chain.

Examples:

class UsersController < BaseController
  def create
    result = User::Create.(user_params) # if this fails the following calls won't run
              .then { |user| User::SendWelcomeEmail.(user: user) }
              .then { |user| User::Login.(user: user) }

    if result.successful?
      json_success(result.value)
    else
      json_error(result.error)
    end
  end
end

Returns:

  • (self)


79
80
81
# File 'lib/f_service/result/failure.rb', line 79

def then
  self
end

#to_sString

Outputs a string representation of the object

Examples:

puts FService::Result::Failure.new("Oh no!")
# => Failure("Oh no!")

Returns:

  • (String)

    the object’s string representation



91
92
93
# File 'lib/f_service/result/failure.rb', line 91

def to_s
  error.nil? ? 'Failure()' : "Failure(#{error.inspect})"
end

#valueObject

Failed operations do not have value.



48
49
50
# File 'lib/f_service/result/failure.rb', line 48

def value
  nil
end

#value!Object

Raises an exception if called. (see #value)

Raises:



54
55
56
# File 'lib/f_service/result/failure.rb', line 54

def value!
  raise Result::Error, 'Failure objects do not have value'
end