/
state_machine.rb
62 lines (43 loc) · 977 Bytes
/
state_machine.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# license is MIT
#
# a state-machine-ish example, inspired by the example at
# http://github.com/qoobaa/transitions
$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'volute'
#
# our classes
module Bookshop
class Book
include Volute
attr_accessor :stock
attr_accessor :discontinued
attr_accessor :state
def initialize (stock)
@stock = stock
@discontinued = false
@state = :in_stock
end
end
end
#
# volutes
volute Bookshop do
volute :stock, :discontinued do
# anything in the module Bookshop that has an attribute :stock
# or :discontinued
if object.stock <= 0
object.state = object.discontinued ? :discontinued : :out_of_stock
else
object.state = :in_stock
end
end
end
#
# trying
emma = Bookshop::Book.new(10)
emma.stock -= 8
p emma.state # => :in_stock
emma.stock -= 2
p emma.state # => :out_of_stock
emma.discontinued = true
p emma.state # => :discontinued