Act as state machine

1,852 views

Published on

Act as state machine description

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,852
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Act as state machine

  1. 1. Acts As State Machine rails plugin <ul><li>What is State diagram ?
  2. 2. State diagrams are used to give an abstract description of the behavior of a system. This behavior is analyzed and represented in series of events, that could occur in one or more possible states. </li></ul>
  3. 3. Acts As State Machine rails plugin <ul><li>Example of State Machine </li></ul>
  4. 4. Acts As State Machine rails plugin <ul><li>Class Article < ActiveRecord::Base
  5. 5. include AASM
  6. 6. aasm_column :state
  7. 7. aasm_initial_state :created
  8. 8. aasm_state :created
  9. 9. aasm_state :published
  10. 10. aasm_state :unpublished
  11. 11. aasm_state :deleted </li></ul>
  12. 12. Acts As State Machine rails plugin <ul>aasm_event :publish do transitions :to => :published, :from => [:created] end aasm_event :unpublish do transitions :to => :unpublished, :from => [:created, :published] end </ul>
  13. 13. Acts As State Machine rails plugin <ul>aasm_event :delete do transitions :to => :deleted, :from => [:published, :unpublished] end aasm_states.each { |s| named_scope s, :conditions => { :state => s.to_s } } end </ul>
  14. 14. Acts As State Machine rails plugin <ul><li>article = Article.new
  15. 15. article.state # nil
  16. 16. article.save # true
  17. 17. article.state # &quot;created&quot;
  18. 18. article.created? # true
  19. 19. article.published? # false </li></ul>
  20. 20. Acts As State Machine rails plugin <ul>Create instance Method , to transition the model from one state to another. <li>article.publish!
  21. 21. article.unpublish!
  22. 22. article.delete! </li></ul>
  23. 23. Acts As State Machine rails plugin <ul><li>Callbacks:
  24. 24. The state also comes with a few callbacks that can be used.
  25. 25. 1. enter
  26. 26. 2.after
  27. 27. 3. exit
  28. 28. state :published, :enter => :do_publish </li></ul>
  29. 29. Acts As State Machine rails plugin <ul><li>Guarding States
  30. 30. Using :guard option you can add some sort of validation for a transition.
  31. 31. Eg:
  32. 32. aasm_event :publish do
  33. 33. transitions :to => :published, :from => [:created], :guard => Proc.new { |article| article.valid?}
  34. 34. end </li></ul>

×