Skip to content

Instantly share code, notes, and snippets.

@guiltry
Last active August 29, 2015 14:19
Show Gist options
  • Save guiltry/8ce827209ece540e2c91 to your computer and use it in GitHub Desktop.
Save guiltry/8ce827209ece540e2c91 to your computer and use it in GitHub Desktop.
class Order < ActiveRecord::Base
after_initialize :change_strategy
def set_paid_strategy(paid_strategy)
@paid_strategy = paid_strategy
end
def set_unpaid_strategy(unpaid_strategy)
@unpaid_strategy = unpaid_strategy
end
def change_strategy
if self.status == Order::PAID
self.set_paid_strategy(PaidOrderPaidStrategy.new)
self.set_unpaid_strategy(PaidOrderUnpaidStrategy.new)
# Commented code below is an example how you can change your paid strategy
# Pure State Pattern can't do it.
# self.set_paid_strategy(PaidOrderPaidStrategyWithoutEmail.new)
elsif self.status == Order::UNPAID
self.set_paid_strategy(UnpaidOrderPaidStrategy.new)
self.set_unpaid_strategy(UnpaidOrderUnpaidStrategy.new)
end
end
def paid!
@paid_strategy.paid!
end
def unpaid!
@unpaid_strategy.unpaid!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment