Class: Karafka::Core::Contractable::Result

Inherits:
Object
  • Object
show all
Defined in:
lib/karafka/core/contractable/result.rb

Overview

Representation of a validaton result with resolved error messages

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(errors, contract) ⇒ Result

Builds a result object and remaps (if needed) error keys to proper error messages

Parameters:

  • errors (Array<Array>)

    array with sub-arrays with paths and error keys

  • contract (Object)

    contract that generated the error



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/karafka/core/contractable/result.rb', line 28

def initialize(errors, contract)
  # Short track to skip object allocation for the happy path
  if errors.empty?
    @errors = EMPTY_HASH
    return
  end

  hashed = {}

  errors.each do |error|
    scope = error.first.map(&:to_s).join(".").to_sym

    # This will allow for usage of custom messages instead of yaml keys if needed
    hashed[scope] = if error.last.is_a?(String)
      error.last
    else
      build_message(contract, scope, error.last)
    end
  end

  @errors = hashed
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



8
9
10
# File 'lib/karafka/core/contractable/result.rb', line 8

def errors
  @errors
end

Class Method Details

.successResult

Returns cached frozen success result to avoid allocating a new Result on every successful contract validation. Safe because successful results are identical regardless of contract (they all have @errors = EMPTY_HASH).

Returns:

  • (Result)

    cached frozen success result to avoid allocating a new Result on every successful contract validation. Safe because successful results are identical regardless of contract (they all have @errors = EMPTY_HASH).



19
20
21
# File 'lib/karafka/core/contractable/result.rb', line 19

def success
  @success ||= new([], nil).freeze
end

Instance Method Details

#success?Boolean

Returns true if no errors.

Returns:

  • (Boolean)

    true if no errors



52
53
54
# File 'lib/karafka/core/contractable/result.rb', line 52

def success?
  errors.empty?
end