Skip to content

Instantly share code, notes, and snippets.

@guiltry
Last active August 29, 2015 14:18
Show Gist options
  • Save guiltry/8d26a58401250e393943 to your computer and use it in GitHub Desktop.
Save guiltry/8d26a58401250e393943 to your computer and use it in GitHub Desktop.
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
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