13. 「安心・安全・安定・信頼」できるインターネットサービスを
ソースコード2
13
require 'state_machine'
class DFA
state_machine :state, :initial => :first do
state :first do
transition :on => :up, :to => :second
end
state :second do
transition :on => :up, :to => :third
transition :on => :down, :to => :first
end
state :third do
transition :on => :down, :to => :second
end
event :up
event :down
end
end
14. 「安心・安全・安定・信頼」できるインターネットサービスを
実行結果
14
dfa = DFA.new
p dfa.state #=> "first"
p dfa.state_events #=> [:up]
p dfa.up #=> true
p dfa.state #=> "second"
p dfa.state_events #=> [:up, :down]
p dfa.up #=> true
p dfa.state #=> "third"
p dfa.state_events #=> [:down]
p dfa.up #=> false
p dfa.state #=> "third"
16. 「安心・安全・安定・信頼」できるインターネットサービスを
app/model/user.rb
16
class User < ActiveRecord::Base
attr_accessible :status
state_machine :status, :initial => :free do
event :normal_charge do
transition :free => :normal
transition :premium => :normal
end
event :premium_charge do
transition :normal => :premium
transition :free => :premium
end
end
end
17. 「安心・安全・安定・信頼」できるインターネットサービスを
実行結果
17
% bundle exec rails c
Loading development environment (Rails 3.2.21)
irb(main):001:0> u = User.create
(0.0ms) begin transaction
SQL (11.7ms) INSERT INTO "users" ("created_at", "status", "updated_at") VALUES (?, ?, ?)
[["created_at", Fri, 16 Jan 2015 15:49:47 UTC +00:00], ["status", "free"], ["updated_at", Fri, 16
2015 15:49:47 UTC +00:00]]
(1.6ms) commit transaction
=> #<User id: 7, status: "free", created_at: "2015-01-16 15:49:47",
updated_at: "2015-01-16 15:49:47">
irb(main):002:0> u.status
=> "free"
irb(main):003:0> u.premium_charge
(0.0ms) begin transaction
(0.3ms) UPDATE "users" SET "status" = 'premium', "updated_at" =
'2015-01-16 15:50:04.353940' WHERE "users"."id" = 7
(2.3ms) commit transaction
=> true
irb(main):004:0> u.status
=> "premium"
irb(main):005:0> u.status_events
=> [:normal_charge]
irb(main):006:0>