examples/state_machine.rb in volute-0.1.0 vs examples/state_machine.rb in volute-0.1.1
- old
+ new
@@ -7,53 +7,55 @@
$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'volute'
#
-# our class
+# our classes
-class Book
- include Volute
+module Bookshop
- attr_accessor :stock
- attr_accessor :discontinued
+ class Book
+ include Volute
- attr_reader :state
+ attr_accessor :stock
+ attr_accessor :discontinued
+ attr_accessor :state
- def initialize (stock)
- @stock = stock
- @discontinued = false
- @state = :in_stock
+ def initialize (stock)
+ @stock = stock
+ @discontinued = false
+ @state = :in_stock
+ end
end
end
#
-# a volute triggered for any 'set' operation on an attribute of book
+# volutes
-volute Book do
+volute Bookshop do
- # object.volute_do_set(:state, x)
- # is equivalent to
- # object.instance_variable_set(:@state, x)
+ volute :stock, :discontinued do
- if object.stock <= 0
- object.volute_do_set(
- :state, object.discontinued ? :discontinued : :out_of_stock)
- else
- object.volute_do_set(
- :state, :in_stock)
+ # 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 = Book.new(10)
+emma = Bookshop::Book.new(10)
-emma.stock = 2
+emma.stock -= 8
p emma.state # => :in_stock
-emma.stock = 0
+emma.stock -= 2
p emma.state # => :out_of_stock
emma.discontinued = true
p emma.state # => :discontinued