Class: ServicePattern::SimpleModelErrors

Inherits:
Service
  • Object
show all
Defined in:
lib/service_pattern/simple_model_errors.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Service

argument, arguments, call, #can_execute?, chain, convert_errors, execute, #execute, execute!, #execute!, fail!, #fail!, #save_models_or_fail, #succeed!

Constructor Details

#initialize(model:, additional_attributes: []) ⇒ SimpleModelErrors

Returns a new instance of SimpleModelErrors.



4
5
6
7
8
9
# File 'lib/service_pattern/simple_model_errors.rb', line 4

def initialize(model:, additional_attributes: [])
  @additional_attributes = additional_attributes
  @model = model
  @errors = []
  @models_inspected = []
end

Instance Attribute Details

#additional_attributesObject (readonly)

Returns the value of attribute additional_attributes.



2
3
4
# File 'lib/service_pattern/simple_model_errors.rb', line 2

def additional_attributes
  @additional_attributes
end

#errorsObject (readonly)

Returns the value of attribute errors.



2
3
4
# File 'lib/service_pattern/simple_model_errors.rb', line 2

def errors
  @errors
end

#modelObject (readonly)

Returns the value of attribute model.



2
3
4
# File 'lib/service_pattern/simple_model_errors.rb', line 2

def model
  @model
end

#models_inspectedObject (readonly)

Returns the value of attribute models_inspected.



2
3
4
# File 'lib/service_pattern/simple_model_errors.rb', line 2

def models_inspected
  @models_inspected
end

Instance Method Details

#inspect_model(model_to_inspect) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/service_pattern/simple_model_errors.rb', line 16

def inspect_model(model_to_inspect)
  return if models_inspected.include?(model_to_inspect)

  model_to_inspect.valid? if model_to_inspect.errors.empty? # Generates the errors on the model so we can detect them
  models_inspected << model_to_inspect

  model_to_inspect.errors.messages.each do |attribute_name, attribute_errors|
    if attribute_name == :base
      @errors += attribute_errors
    else
      next if model_to_inspect.attribute_names.exclude?(attribute_name.to_s) && additional_attributes.exclude?(attribute_name)

      attribute_errors.each do |message|
        errors << "#{model_to_inspect.class.human_attribute_name(attribute_name)} #{message}"
      end
    end
  end

  collect_errors_from_associations(model_to_inspect)
end

#performObject



11
12
13
14
# File 'lib/service_pattern/simple_model_errors.rb', line 11

def perform
  inspect_model(model)
  succeed!(errors)
end