Class: Spree::Workflow
- Inherits:
-
Object
- Object
- Spree::Workflow
- Extended by:
- ActiveModel::Naming, ActiveModel::Translation
- Includes:
- ServiceModule::Base, ControlFlow
- Defined in:
- lib/spree/workflow.rb
Overview
Workflow — Tier 2 of the services doctrine (docs/plans/6.0-service-workflows.md): named steps inside a plain #perform method, the ActiveJob::Continuable shape.
class Spree::Orders::Cancel < Spree::Workflow
hooks :after_cancel
attr_reader :cancellation # derived state hook handlers may read
# @param order [Spree::Order] the order to cancel
def perform(order:, canceler: nil, reason: 'other')
super
step :ensure_cancellable
ApplicationRecord.transaction do
step :record_cancellation
run_hooks :after_cancel
end
external_step :settle_payments
order.publish_event('order.canceled')
success(order.reload)
rescue ActiveRecord::RecordInvalid
failure(order)
end
end
The #perform signature IS the argument contract: Ruby itself raises on
missing or unknown keywords, YARD documents it. A bare super first
assigns every parameter — defaults applied — to an instance variable
with a public reader, so step bodies and hook handlers read plain
methods. Everything else is ordinary Rails: plain transactions and
locks, plain if, plain rescue, publish_event for announcements.
The workflow vocabulary is five words. step :name runs the method of
that name (instrumented as 'step.spree_workflow'); on_flow_failure:
names its undo, armed when the surrounding transaction commits and run
in reverse when a later step fails; with: delegates the step to a
collaborator resolved from the lambda, its keyword arguments sliced
from this workflow's readers. external_step marks gateway/network
I/O and refuses to run inside a database transaction. run_hooks
dispatches a declared extension point (see .hooks) with the workflow
instance. failure(...) aborts the flow from anywhere — it raises
internally, so an open plain transaction rolls back naturally — and
halt!(value) is its successful twin (outside transactions only).
Direct Known Subclasses
Carts::AddItem, Carts::Complete, Carts::Merge, Carts::Recalculate, Carts::RecalculateTotals, Carts::UpsertItems, Catalogs::Activate, Catalogs::Create, Catalogs::Deactivate, Catalogs::SetPriceList, Catalogs::Update, Claims::Approve, Claims::Cancel, Claims::Create, Claims::Deny, Claims::Resolve, Customers::Anonymize, Customers::Create, DataRequests::Fulfill, Deliveries::UpdateTracking, DigitalAssets::Create, DigitalAssets::Update, EmailTemplates::DiscardDraft, EmailTemplates::Publish, EmailTemplates::RestoreRevision, EmailTemplates::Revert, EmailTemplates::SaveDraft, Exchanges::Approve, Exchanges::Cancel, Exchanges::Create, Exchanges::Fulfill, Exchanges::Receive, Fulfillments::Cancel, Fulfillments::Create, Fulfillments::Fulfill, Fulfillments::MarkDelivered, Fulfillments::Update, GiftCards::Apply, GiftCards::Cancel, GiftCards::Destroy, GiftCards::Redeem, GiftCards::Remove, Imports::Complete, Imports::CompleteMapping, Imports::RetryFailedRows, Imports::StartMapping, Imports::StartProcessing, Invitations::Accept, Orders::Cancel, Orders::Complete, Orders::Create, PaymentSessions::Complete, Payments::Capture, Payments::HandleModificationWebhook, Payments::HandleWebhook, Payments::Process, Payments::Void, PriceLists::Activate, PriceLists::Create, PriceLists::Deactivate, PriceLists::Update, Products::Activate, Products::Approve, Products::Archive, Products::Create, Products::Destroy, Products::Draft, Products::Propose, Products::Reject, Products::Update, PurchaseOrders::Cancel, PurchaseOrders::Close, PurchaseOrders::Create, PurchaseOrders::MarkDraft, PurchaseOrders::MarkOrdered, PurchaseOrders::Receive, PurchaseOrders::Update, Refunds::Create, Returns::Approve, Returns::Cancel, Returns::Create, Returns::Receive, Returns::Refund, SellerPayouts::Complete, SellerPayouts::Sweep, SellerRequirementSubmissions::Accept, SellerRequirementSubmissions::Create, SellerRequirementSubmissions::Reject, SellerRequirementSubmissions::Waive, SellerTransfers::Create, SellerTransfers::Reverse, Sellers::Approve, Sellers::Create, Sellers::Invite, Sellers::Reject, Sellers::ReopenOnboarding, Sellers::StartOnboarding, Sellers::SubmitForReview, Sellers::Suspend, ShippingLabels::Purchase, ShippingLabels::Record, ShippingLabels::Refund, StockLevels::BulkUpsert, StockTransfers::Cancel, StockTransfers::Close, StockTransfers::Create, StockTransfers::MarkDraft, StockTransfers::MarkInTransit, StockTransfers::MarkReady, StockTransfers::Receive, StockTransfers::Update, TaxExemptionCertificates::Verify, Variants::Create, Variants::Update
Defined Under Namespace
Modules: ControlFlow Classes: ContractError, FailureSignal, Halted
Class Attribute Summary collapse
-
.declared_hooks ⇒ Object
readonly
Returns the value of attribute declared_hooks.
Class Method Summary collapse
-
.define_argument_readers(names) ⇒ Object
Public readers for #perform's parameters, memoized per class.
-
.hooks(*names) ⇒ Object
Declares the extension points this workflow dispatches via run_hooks.
-
.inherited(subclass) ⇒ Object
A subclass inherits the parent's declared hooks but dispatches them under its OWN key — Spree::Orders::AddItem fires 'orders.add_item.validate', not the cart key — so it registers itself too, otherwise Spree.hooks.validate! rejects registrations against a twin's perfectly valid hook.
-
.model_name ⇒ Object
Anonymous test doubles have no name to derive a model name from.
-
.workflow_key(value = nil) ⇒ Object
Dotted identity used for hook keys and instrumentation; derived from the class name (Spree::Carts::AddItem => 'carts.add_item') unless set explicitly.
Instance Method Summary collapse
- #call(**kwargs) ⇒ Object
-
#errors ⇒ ActiveModel::Errors
Rejections a handler collected, rendered by the API through the same path as model validation errors — an extension veto and a failed
validatesproduce the same 422 shape. -
#halt!(value) ⇒ Object
Successful early exit from anywhere — the caller receives success(value).
-
#perform(**arguments) ⇒ Object
Bare
superfrom the subclass's #perform lands here with the parameter values as currently bound — defaults applied — and turns each into an ivar + public reader. -
#read_attribute_for_validation(attribute) ⇒ Object
ActiveModel::Errors reads attribute values off its base when interpolating a message; a workflow's "attributes" are its argument readers, and an error on an attribute the workflow doesn't expose (:base, or a field name belonging to the record) must not raise.
-
#reject!(message = nil, value = nil, **options) ⇒ Object
Vetoes the flow from a hook handler — the extension-facing twin of failure(...).
Methods included from ServiceModule::Base
Methods included from ControlFlow
Class Attribute Details
.declared_hooks ⇒ Object (readonly)
Returns the value of attribute declared_hooks.
92 93 94 |
# File 'lib/spree/workflow.rb', line 92 def declared_hooks @declared_hooks end |
Class Method Details
.define_argument_readers(names) ⇒ Object
Public readers for #perform's parameters, memoized per class. An author-defined method of the same name wins.
Note for workflow authors: inside #perform, a parameter name is a
local variable and shadows the reader, so a step that reassigns the
ivar (@product = ...) is invisible to success(product) further
down. Name derived state differently from the parameter that seeded
it — Carts::AddItem takes variant and exposes line_item.
135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/spree/workflow.rb', line 135 def define_argument_readers(names) @argument_readers ||= {} names.each do |name| next if @argument_readers[name] @argument_readers[name] = true next if method_defined?(name) || private_method_defined?(name) define_method(name) { instance_variable_get(:"@#{name}") } end end |
.hooks(*names) ⇒ Object
Declares the extension points this workflow dispatches via run_hooks. Class-level so Spree.hooks.validate! can fail boot on registrations against hooks that don't exist.
122 123 124 125 |
# File 'lib/spree/workflow.rb', line 122 def hooks(*names) @declared_hooks = (declared_hooks || []) | names.map(&:to_sym) Spree.hooks.register_workflow(workflow_key, self.name) end |
.inherited(subclass) ⇒ Object
A subclass inherits the parent's declared hooks but dispatches them under its OWN key — Spree::Orders::AddItem fires 'orders.add_item.validate', not the cart key — so it registers itself too, otherwise Spree.hooks.validate! rejects registrations against a twin's perfectly valid hook.
104 105 106 107 108 109 |
# File 'lib/spree/workflow.rb', line 104 def inherited(subclass) super inherited_hooks = (declared_hooks || []).dup subclass.instance_variable_set(:@declared_hooks, inherited_hooks) Spree.hooks.register_workflow(subclass.workflow_key, subclass.name) if inherited_hooks.any? && subclass.name end |
.model_name ⇒ Object
Anonymous test doubles have no name to derive a model name from.
95 96 97 |
# File 'lib/spree/workflow.rb', line 95 def model_name @model_name ||= ActiveModel::Name.new(self, nil, name || 'Workflow') end |
.workflow_key(value = nil) ⇒ Object
Dotted identity used for hook keys and instrumentation; derived from the class name (Spree::Carts::AddItem => 'carts.add_item') unless set explicitly.
114 115 116 117 |
# File 'lib/spree/workflow.rb', line 114 def workflow_key(value = nil) @workflow_key = value.to_s if value @workflow_key ||= name.delete_prefix('Spree::').split('::').map(&:underscore).join('.') end |
Instance Method Details
#call(**kwargs) ⇒ Object
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/spree/workflow.rb', line 156 def call(**kwargs) @undo_stack = [] @outer_transaction_depth = ApplicationRecord.connection.open_transactions ActiveSupport::Notifications.instrument( 'perform.spree_workflow', workflow: self.class.workflow_key ) do |payload| outcome = perform(**kwargs) result = outcome.is_a?(Spree::ServiceModule::Result) ? outcome : success(outcome) payload[:outcome] = result.success? ? 'success' : 'failure' result rescue Halted => halted payload[:outcome] = 'success' success(halted.value) rescue FailureSignal => signal payload[:outcome] = 'failure' run_undo_stack! signal.result rescue StandardError payload[:outcome] = 'error' run_undo_stack! raise end end |
#errors ⇒ ActiveModel::Errors
Rejections a handler collected, rendered by the API through the same
path as model validation errors — an extension veto and a failed
validates produce the same 422 shape.
197 198 199 |
# File 'lib/spree/workflow.rb', line 197 def errors @errors ||= ActiveModel::Errors.new(self) end |
#halt!(value) ⇒ Object
Successful early exit from anywhere — the caller receives success(value). Not from inside a transaction the workflow itself opened: there is nothing committed to halt with (use failure to roll back). A transaction the caller wrapped around the whole run is theirs to commit and doesn't count.
186 187 188 189 190 |
# File 'lib/spree/workflow.rb', line 186 def halt!(value) raise ContractError, 'halt! cannot be called inside a database transaction' if in_workflow_transaction? raise Halted.new(value) end |
#perform(**arguments) ⇒ Object
Bare super from the subclass's #perform lands here with the
parameter values as currently bound — defaults applied — and turns
each into an ivar + public reader.
151 152 153 154 |
# File 'lib/spree/workflow.rb', line 151 def perform(**arguments) arguments.each { |name, value| instance_variable_set(:"@#{name}", value) } self.class.define_argument_readers(arguments.keys) end |
#read_attribute_for_validation(attribute) ⇒ Object
ActiveModel::Errors reads attribute values off its base when interpolating a message; a workflow's "attributes" are its argument readers, and an error on an attribute the workflow doesn't expose (:base, or a field name belonging to the record) must not raise.
207 208 209 |
# File 'lib/spree/workflow.rb', line 207 def read_attribute_for_validation(attribute) respond_to?(attribute) ? public_send(attribute) : nil end |
#reject!(message = nil, value = nil, **options) ⇒ Object
Vetoes the flow from a hook handler — the extension-facing twin of failure(...). Same mechanics (raises, unwinds the undo stack, rolls back an open transaction); the distinct name keeps "an extension rejected this" legible against "this step failed" at the call site. Public because handlers call it on the dispatched instance.
Preferred form is argument-less, after adding symbolic errors:
workflow.errors.add(:quantity, :purchase_limit_exceeded, message: '…')
workflow.reject!
229 230 231 232 |
# File 'lib/spree/workflow.rb', line 229 def reject!( = nil, value = nil, **) errors.add(:base, , **) if .present? failure(value, errors) end |