Class: PackAPI::Types::Result

Inherits:
Dry::Struct
  • Object
show all
Defined in:
lib/pack_api/types/result.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_collection(models:, value_object_factory:, optional_attributes: nil, paginator: nil, sort: nil, current_page_snapshot_cursor: nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pack_api/types/result.rb', line 14

def self.from_collection(models:,
                         value_object_factory:,
                         optional_attributes: nil,
                         paginator: nil,
                         sort: nil,
                         current_page_snapshot_cursor: nil)
  value = value_object_factory.create_collection(models:, optional_attributes:)
  if paginator.present?
     = CollectionResultMetadata.from_paginator(paginator, sort, current_page_snapshot_cursor)
  end

  new(
    success: true,
    value:,
    collection_metadata:
  )
end

.from_model(model:, value_object_factory:, optional_attributes: nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/pack_api/types/result.rb', line 32

def self.from_model(model:, value_object_factory:, optional_attributes: nil)
  if model.errors.present?
    errors = value_object_factory.create_errors(model:)
    errors[:request] = model.errors[:base] if model.errors[:base].present?
    new(
      success: false,
      errors:
    )
  else
    new(
      success: true,
      value: value_object_factory.create_object(model:, optional_attributes:)
    )
  end
end

.from_request_error(message, model: nil) ⇒ Object



10
11
12
# File 'lib/pack_api/types/result.rb', line 10

def self.from_request_error(message, model: nil)
  new(success: false, errors: { request: [message] }, value: model)
end

Instance Method Details

#attribute_error_string(attribute) ⇒ Object



48
49
50
51
52
# File 'lib/pack_api/types/result.rb', line 48

def attribute_error_string(attribute)
  return '' if errors.nil? || errors[attribute].blank?

  errors[attribute]&.join(', ')
end

#error_stringObject



60
61
62
63
64
65
66
67
68
# File 'lib/pack_api/types/result.rb', line 60

def error_string
  return '' if errors.nil?

  one_message_per_error = errors.map do |attribute, errors|
    "#{attribute.to_s.titleize}: #{Array.wrap(errors).join(', ')}"
  end

  one_message_per_error.join(', ')
end

#request_error_stringObject



54
55
56
57
58
# File 'lib/pack_api/types/result.rb', line 54

def request_error_string
  return '' if errors.nil? || errors[:request].blank?

  "#{errors[:request]&.join(', ')}."
end