Class: Spree::ExternalReference

Inherits:
Object
  • Object
show all
Includes:
Metadata, SingleStoreResource
Defined in:
app/models/spree/external_reference.rb

Overview

Maps a Spree record to its identity in an external system — the key an ERP, PIM, DAM or CRM knows it by. A record can carry one reference per system, so a product known to both a PIM and an ERP under different keys needs no per-system column.

system is a plain string key rather than a foreign key to Integration: data arrives from systems that have no live connector (a nightly CSV from a legacy PIM), and those still need somewhere to record their identity. Where a connector does exist the convention is to reuse its integration's api_type, so connector, references and settings page agree on the name.

Class Method Summary collapse

Methods included from Metadata

#private_metadata, #private_metadata=

Class Method Details

.normalize_references(references) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/models/spree/external_reference.rb', line 44

def self.normalize_references(references)
  return [] if references.blank?

  entries =
    if references.is_a?(Hash) && !references.key?(:system) && !references.key?('system')
      references.map { |system, external_id| { system: system, external_id: external_id } }
    else
      Array(references).map { |entry| entry.respond_to?(:to_unsafe_h) ? entry.to_unsafe_h : entry }
    end

  entries.filter_map do |entry|
    entry = entry.to_h.symbolize_keys.slice(:system, :external_id, :metadata)
    entry[:system].blank? ? nil : entry
  end
end

.normalize_system(value) ⇒ Array<Hash>, String

Turns either shape a caller may hold — the { system => external_id } map the admin serializers render, or a [{ system:, external_id: }] list — into symbolized entries, dropping any that name no system.

The single definition of the accepted shapes: the write path (HasExternalReferences#assign_external_references) and the API concern's upsert lookup both parse payloads through here.

The one statement of what a system key looks like: every lookup and write normalizes through here, or a writer's key and a reader's key could disagree about the same row.

Parameters:

  • references (Hash, Array<Hash>, nil)

Returns:

  • (Array<Hash>) —

    entries with :system, :external_id and optional :metadata

  • (String)


40
41
42
# File 'app/models/spree/external_reference.rb', line 40

def self.normalize_system(value)
  value.to_s.strip.downcase
end