Class: Spree::Catalogs::SetAssignments

Inherits:
Object
  • Object
show all
Includes:
ServiceModule::Base
Defined in:
app/services/spree/catalogs/set_assignments.rb

Overview

Replaces a catalog's audience with the given set.

An audience absent from the payload is withdrawn, so the whole set arrives in one request — the agreement editor stages every change behind the catalog's Save, and applying half of them would show the agreement to people the merchant never confirmed.

Instance Method Summary collapse

Methods included from ServiceModule::Base

prepended

Instance Method Details

#call(catalog:, assignables:) ⇒ Spree::ServiceModule::Result

Returns value is the catalog.

Parameters:

Returns:



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/services/spree/catalogs/set_assignments.rb', line 17

def call(catalog:, assignables:)
  keys = Array(assignables).map { |record| [record.class.base_class.name, record.id] }
  invalid = nil

  ApplicationRecord.transaction do
    withdraw(catalog, keys)

    keys.zip(Array(assignables)).each do |(type, id), record|
      next if catalog.catalog_assignments.exists?(assignable_type: type, assignable_id: id)

      assignment = catalog.catalog_assignments.new(assignable: record)
      next if assignment.save

      # A plain service's `failure` returns rather than raising, so one
      # bad row has to take the transaction down itself — otherwise the
      # rest of the set commits and the caller is told it all worked.
      invalid = assignment
      raise ActiveRecord::Rollback
    end
  end

  return failure(invalid) if invalid

  success(catalog.reload)
end