Module: Spree::HasNumber
- Extended by:
- ActiveSupport::Concern
- Included in:
- Base
- Defined in:
- app/models/concerns/spree/has_number.rb
Overview
Declarative human-readable document number for models whose number is shown to a person — on an order confirmation, a supplier purchase order, a transfer slip taped to a box (docs/plans/6.0-document-numbers.md).
class Spree::Order < Spree.base_class
has_spree_number prefix: 'R'
end
Included into Base, so the macro is available on every model and nothing happens until one calls it — no callback, no class attributes.
The concern owns the parts that never vary: assigning a number before validation, retrying on collision, and rescuing the unique-index race. Which string to try is the generator's job, and the generator is resolved per record at save time rather than frozen at class-definition time — that is what lets a merchant switch formats in settings, and an extension swap the whole strategy through #number_generators, without reopening this class.
Defined Under Namespace
Classes: GenerationError
Constant Summary collapse
- MAX_ATTEMPTS =
A generator that keeps colliding is a bug in the generator, not bad luck. Bail loudly rather than spinning in a save.
10
Instance Method Summary collapse
-
#generate_number ⇒ String
Assigns a number unless one was supplied.
-
#number_store ⇒ Spree::Store?
The store whose number settings apply.
Instance Method Details
#generate_number ⇒ String
Assigns a number unless one was supplied. Public so a workflow can force assignment before validation when it needs the number earlier.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'app/models/concerns/spree/has_number.rb', line 66 def generate_number return number if number.present? generator = self.class.number_generator(store: number_store) MAX_ATTEMPTS.times do candidate = generator.generate(self) next if candidate.blank? unless number_taken?(candidate) @number_generated = true return self.number = candidate end end raise GenerationError, "#{self.class.name} could not generate a unique number after " \ "#{MAX_ATTEMPTS} attempts using #{generator.class.name}" end |
#number_store ⇒ Spree::Store?
The store whose number settings apply. Most numbered models belong to a store directly; stock transfers reach one through their destination location. Falls back to the current store so a numbered model added later works without teaching this concern about it.
92 93 94 95 96 |
# File 'app/models/concerns/spree/has_number.rb', line 92 def number_store return store if respond_to?(:store) && store.present? Spree::Current.store end |