Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce state vo #367

Merged
merged 11 commits into from
Aug 6, 2024
54 changes: 42 additions & 12 deletions ecommerce/ordering/lib/ordering/order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ class Order

def initialize(id)
@id = id
@state = :draft
@state = State.draft
@basket = Basket.new
end

def submit(order_number)
raise OrderHasExpired if @state.equal?(:expired)
raise AlreadySubmitted unless @state.equal?(:draft)
raise OrderHasExpired if @state.expired?
raise AlreadySubmitted unless @state.draft?
apply OrderSubmitted.new(
data: {
order_id: @id,
Expand All @@ -26,7 +26,7 @@ def submit(order_number)
end

def accept
raise InvalidState unless @state.equal?(:submitted)
raise InvalidState unless @state.submitted?
apply OrderPlaced.new(
data: {
order_id: @id,
Expand All @@ -37,7 +37,7 @@ def accept
end

def reject
raise InvalidState unless @state.equal?(:submitted)
raise InvalidState unless @state.submitted?
apply OrderRejected.new(
data: {
order_id: @id
Expand All @@ -46,12 +46,12 @@ def reject
end

def expire
raise AlreadySubmitted unless @state.equal?(:draft)
raise AlreadySubmitted unless @state.draft?
apply OrderExpired.new(data: { order_id: @id })
end

def add_item(product_id)
raise AlreadySubmitted unless @state.equal?(:draft)
raise AlreadySubmitted unless @state.draft?
apply ItemAddedToBasket.new(
data: {
order_id: @id,
Expand All @@ -61,16 +61,16 @@ def add_item(product_id)
end

def remove_item(product_id)
raise AlreadySubmitted unless @state.equal?(:draft)
raise AlreadySubmitted unless @state.draft?
apply ItemRemovedFromBasket.new(data: { order_id: @id, product_id: product_id })
end

on OrderPlaced do |event|
@state = :accepted
@state = State.new(:accepted)
end

on OrderExpired do |event|
@state = :expired
@state = State.expired
end

on ItemAddedToBasket do |event|
Expand All @@ -83,11 +83,11 @@ def remove_item(product_id)

on OrderSubmitted do |event|
@order_number = event.data[:order_number]
@state = :submitted
@state = State.submitted
end

on OrderRejected do |event|
@state = :draft
@state = State.draft
end

class Basket
Expand All @@ -112,5 +112,35 @@ def quantity(product_id)
order_lines[product_id]
end
end

class State
def self.draft
new(:draft)
end

def self.submitted
new(:submitted)
end

def self.expired
new(:expired)
end

def initialize(state)
@state = state
end

def draft?
@state.equal?(:draft)
end

def submitted?
@state.equal?(:submitted)
end

def expired?
@state.equal?(:expired)
end
end
end
end
Loading