Last active
January 8, 2018 15:45
-
-
Save daniel-bytes/b19a68a5b8f154445a4160904601699d to your computer and use it in GitHub Desktop.
Product model with AASM state machine
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 Product | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
include AASM | |
field :name, type: String | |
field :state, type: String | |
field :price, type: Integer | |
field :inventory, type: Integer, default: 0 | |
index({ name: 1 }, { unique: true }) | |
aasm(column: :state, with_klass: StateTracking) do | |
enable_tracking! | |
state :initialized, initial: true | |
state :created | |
state :in_stock | |
state :out_of_stock | |
state :discountinued | |
event :create do | |
transitions :from => :initialized, | |
:to => :created | |
end | |
event :add_inventory do | |
transitions :from => [:created, :in_stock, :out_of_stock], | |
:to => :in_stock | |
end | |
event :reduce_inventory do | |
transitions :from => :in_stock, | |
:to => :in_stock, | |
:guard => :has_inventory? | |
transitions :from => :in_stock, | |
:to => :out_of_stock | |
end | |
event :discontinue do | |
transitions :from => [:created, :in_stock, :out_of_stock], | |
:to => :discountinued | |
end | |
end | |
def has_inventory? | |
inventory > 0 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment