Class: ServicePattern::ModelsSave

Inherits:
Service
  • Object
show all
Defined in:
lib/service_pattern/models_save.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(models:, simple_model_errors: true) ⇒ ModelsSave

Returns a new instance of ModelsSave.



4
5
6
7
# File 'lib/service_pattern/models_save.rb', line 4

def initialize(models:, simple_model_errors: true)
  @models = models
  @simple_model_errors = simple_model_errors
end

Instance Attribute Details

#modelsObject (readonly)

Returns the value of attribute models.



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

def models
  @models
end

#simple_model_errorsObject (readonly)

Returns the value of attribute simple_model_errors.



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

def simple_model_errors
  @simple_model_errors
end

Instance Method Details

#performObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/service_pattern/models_save.rb', line 9

def perform
  errors = []

  models.first.transaction do
    models.each do |model|
      next if model.save

      if simple_model_errors
        errors += ServicePattern::SimpleModelErrors.execute!(model: model)
      else
        errors += models.map(&:errors).map(&:full_messages).flatten
      end

      raise ActiveRecord::Rollback if errors.any?
    end
  end

  fail! errors.uniq if errors.any?
  succeed!
end