Class: Spree::DeliveryMethodRules::ExcludedProductsRule

Inherits:
Spree::DeliveryMethodRule show all
Defined in:
app/models/spree/delivery_method_rules/excluded_products_rule.rb

Overview

Blocks the method for packages containing any of the attached products ("fragile item can't ship express"). Products hang off the concrete spree_delivery_method_rule_products join table — catalog-scale references never live in preferences. A rule with no products passes, matching the empty-preference fail-open convention.

Instance Method Summary collapse

Methods included from TypeLabels

#human_description, #human_name

Methods included from PreferenceSchema

#serialized_preferences

Instance Method Details

#eligible?(package) ⇒ Boolean

Asks whether any of the package's products is excluded, rather than loading the whole exclusion list — the join table's composite index answers it without transferring rows.

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/models/spree/delivery_method_rules/excluded_products_rule.rb', line 30

def eligible?(package)
  product_ids = package.contents.map { |item| item.variant.product_id }.uniq
  return true if product_ids.empty?

  # `target` is whatever is already in memory, so reading it never
  # triggers a load. It covers links assigned but not yet saved — the
  # admin controller assigns products before saving the rule.
  return false if delivery_method_rule_products.target.any? { |link|
    link.new_record? && product_ids.include?(link.product_id)
  }
  # An unsaved rule has no rows to query, and asking would still cost a
  # round trip.
  return true if new_record?

  !delivery_method_rule_products.exists?(product_id: product_ids)
end

#product_prefixed_ids ⇒ Array<String>

Excluded product ids in prefixed form. Plucked rather than hydrating N Product rows just to re-encode their ids, but read through the products association so soft-deleted products drop out — a client resubmitting this list must not be told a product it never chose is unreachable. Sorted so clients can compare a response against what they sent.

Returns:

  • (Array<String>)


23
24
25
# File 'app/models/spree/delivery_method_rules/excluded_products_rule.rb', line 23

def product_prefixed_ids
  products.pluck(:id).sort.map { |id| Spree::Product.prefixed_id_for(id) }
end