Module: Spree::HasAddressBook

Extended by:
ActiveSupport::Concern
Included in:
Company
Defined in:
app/models/concerns/spree/has_address_book.rb

Overview

Anything that keeps an address book: a customer, a company node, and whatever comes next.

Owners already differ in what they call their default slots — a customer has bill_address_id / ship_address_id, a company node default_bill_address_id / default_ship_address_id — so the columns are declared once here and every caller asks the owner instead of knowing which of them it is holding.

class Spree::Company < Spree.base_class
has_address_book bill: :default_bill_address_id, ship: :default_ship_address_id
end

Instance Method Summary collapse

Instance Method Details

#assign_default_address(address_id:, billing: true, shipping: true) ⇒ Object

Points this owner's default slots at an address.

Writes the columns directly: callers have already established that the address is this owner's, so the ownership validation this skips cannot fail, and skipping it avoids re-running a whole validation set to move one foreign key.

Each flag has three meanings, and they are all different: true promotes this address, false gives up the slot — but only when this address is what currently holds it, since another entry's default is not this caller's business — and nil leaves the slot alone.

Parameters:

  • address_id (Integer)
  • billing (Boolean, nil) (defaults to: true) —

    promote to, or release, the billing slot

  • shipping (Boolean, nil) (defaults to: true) —

    promote to, or release, the shipping slot



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/models/concerns/spree/has_address_book.rb', line 40

def assign_default_address(address_id:, billing: true, shipping: true)
  promoted = {}
  released = []

  { bill: billing, ship: shipping }.each do |kind, flag|
    column = default_address_columns[kind]

    if flag
      promoted[column] = address_id
    elsif flag == false
      released << column
    end
  end

  promote_default_columns(promoted)
  release_default_columns(released, address_id)

  # Promotion writes the in-memory attributes on its way through; a
  # release goes around them, so only that leaves this instance stale.
  reload if persisted? && released.any?
end

#default_address_id(kind) ⇒ Integer?

Returns the address this owner prefills that slot with.

Parameters:

  • kind (Symbol) —

    :bill or :ship

Returns:

  • (Integer, nil) —

    the address this owner prefills that slot with



64
65
66
# File 'app/models/concerns/spree/has_address_book.rb', line 64

def default_address_id(kind)
  public_send(default_address_columns.fetch(kind))
end