こんちには、おがしょーです。
今回は自分の備忘録のためのエントリです。
ユーザー認証などでRestfulAuthenticationを使う場合、ステートマシンとして2種類のモジュールが使える。
1. acts_as_state_machine
2. AASM (rubyist-aasm)
※今回の流れ。
ググって出てくる参考サイトではほとんどacts_as_state_machineを使用していたので、迷い無くこれをチョイス。
↓
プラグインはGitHubからのインストールでまとめたいので探してみる、が見つからない。
↓
実は長い間アップデートされてない。
↓
後継でAASMなるものを発見。
↓
rubyist-aasmをインストールした後、RestfulAuthenticationをAASMに切り替える。
↓
find_in_stateがエラーになる。
↓
そういえばacts_as_state_machineに複数状態を指定できるパッチ当ててたっけ。。
引用元: kaeruspoon様
module ScottBarron
module Acts
module StateMachine
module ClassMethods
protected
def with_state_scope(target_states)
target_states = [target_states] unless target_states.is_a?(Array)
raise InvalidState unless target_states.all? {|s| states.include?(s)}
cond = []
cond_param = []
target_states.each do |st|
cond << "#{table_name}.#{state_column} = ?"
cond_param < {:conditions => [cond.join(" OR "), cond_param].flatten} do
yield if block_given?
end
end
end
end
end
end
↓AASM用に変更してみる・・・が、動かない。AASMがgemだからか??
↓
メソッド名を変えてリトライ。
[ RAILS/config/initializers/patch_aasm.rb ]
module AASM
module Persistence
module ActiveRecordPersistence
module ClassMethods
def find_in_states(number, state, *args)
with_states_scope state do
find(number, *args)
end
end
def count_in_states(state, *args)
with_states_scope state do
count(*args)
end
end
def calculate_in_states(state, *args)
with_states_scope state do
calculate(*args)
end
end
protected
def with_states_scope(target_states)
target_states = [target_states] unless target_states.is_a?(Array)
raise InvalidState unless target_states.all? {|s| aasm_states.include?(s)}
cond = []
cond_param = []
target_states.each do |st|
cond << "?"
cond_param < {:conditions => ["#{table_name}.#{aasm_column} IN (#{cond.join(', ')})", cond_param].flatten} do
yield if block_given?
end
end
end
end
end
end
↓できた (n’∀’)η
まだgemとかよくわかってないのGitHubでForkして修正して・・・とかやりたかったけど無理でした。
先は長いなぁ〜。
おまけ。
ステートマシンについてはこちらのページが詳しいです。
境界を越える: Rails での拡張