Class: ActiveInteractor::Result

Inherits:
Object
  • Object
show all
Includes:
HasActiveModelErrors
Defined in:
lib/active_interactor/result.rb

Constant Summary collapse

STATUS =
{
  success: 0,
  failed_at_input: 1,
  failed_at_runtime: 2,
  failed_at_output: 3
}.freeze

Instance Attribute Summary collapse

Attributes included from HasActiveModelErrors

#errors

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status:, data: {}) ⇒ Result

Returns a new instance of Result.



47
48
49
50
51
# File 'lib/active_interactor/result.rb', line 47

def initialize(status:, data: {})
  @status = status
  @data = data
  @errors = ActiveModel::Errors.new(self)
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



16
17
18
# File 'lib/active_interactor/result.rb', line 16

def data
  @data
end

Class Method Details

.failure(data: {}, errors: {}, status: STATUS[:failed_at_runtime]) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/active_interactor/result.rb', line 23

def failure(data: {}, errors: {}, status: STATUS[:failed_at_runtime])
  result = new(status: status, data: data)
  parse_errors(errors).each_pair do |attribute, messages|
    Array.wrap(messages).each { |message| result.errors.add(attribute, message) }
  end
  result
end

.success(data: {}) ⇒ Object



19
20
21
# File 'lib/active_interactor/result.rb', line 19

def success(data: {})
  new(status: STATUS[:success], data: data)
end

Instance Method Details

#failure?Boolean Also known as: failed?

Returns:

  • (Boolean)


53
54
55
# File 'lib/active_interactor/result.rb', line 53

def failure?
  !success?
end

#read_attribute_for_validation(attribute_name) ⇒ Object



58
59
60
# File 'lib/active_interactor/result.rb', line 58

def read_attribute_for_validation(attribute_name)
  data.send(attribute_name.to_sym)
end

#success?Boolean Also known as: successful?

Returns:

  • (Boolean)


62
63
64
# File 'lib/active_interactor/result.rb', line 62

def success?
  @status == STATUS[:success]
end

#to_hashObject Also known as: to_h



67
68
69
70
71
72
73
# File 'lib/active_interactor/result.rb', line 67

def to_hash
  {
    success: success?,
    errors: errors.to_hash,
    data: data.to_hash
  }
end