Last active
August 29, 2015 14:18
-
-
Save guiltry/8d26a58401250e393943 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Order < ActiveRecord::Base | |
after_initialize :change_state | |
def set_state(order_state) | |
@state = order_state | |
end | |
def change_state | |
# we keep this logic block, to choose what state logic the object use at initialization | |
if self.status == Order::PAID | |
self.set_state(OrderPaidState.new) | |
elsif self.status == Order::UNPAID | |
self.set_state(OrderUnpaidState.new) | |
end | |
end | |
def paid! | |
@state.paid! | |
end | |
def unpaid! | |
@state.unpaid! | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OrderUnpaidState | |
def unpaid!(order) | |
# do nothing or raise an error | |
end | |
def paid!(order) | |
# sent email, change status, ... | |
order.set_state(OrderPaidState.new) | |
end | |
end | |
class OrderPaidState | |
def unpaid!(order) | |
# sent email, change status, ... | |
order.set_state(OrderUnpaidState.new) | |
end | |
def paid!(order) | |
# do nothing or raise an error | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment