2015-11-03 73 views
0

目前,我試圖找出如何在我的Rails應用程序中處理狀態的最佳方式。在Rails中處理多個狀態

我有一個模型(繪圖),它在三個維度處理多個狀態。

  • 有效/無效
  • 開始/運行/結束
  • not_full /全

有五種狀態,我需要處理:

  • 不活躍&所有其他國家
  • 活動& n ot_started & not_full
  • 活躍&運行& not_full
  • 活躍&運行&全
  • 活躍&結束&全

有人能指出我到關於寶石使用或文章讀給正確的方向詳細瞭解如何在Rails中處理狀態? 這是將不同的屬性與狀態結合的正確方法嗎? 我是否必須分別定義每個轉換?

+0

我認爲處理統計信息的最好方法是使用狀態機gem。 我一直想將這個應用到我現有的應用一段時間,但其他的事情優先。 https://github.com/pluginaweek/state_machine 我想這會讓每個人都受益,一旦你得到這個工作,你回到這裏並報告。 ;) – Doctor06

回答

1

我通常不會使用gem來處理狀態機,因爲我通常必須微調通常超越gem功能的訪問和轉換。相反,我只需要在散列中定義關於狀態機的所有信息,然後在模型中創建方法來處理定義。

class Draw 
     STATES = { 
     inactive: { 
      label: "Inactive", 
      transition: ->(draw) { 
      # code here that handles the transition to inactive state 
      } 
      from: [:started, :running, :ended], 
      guard: ->(draw) { 
      # code here that indicates that this state can be transitioned 
into 
      !self.running? 
      } 
     } 
     started: { 
      # as above 
     } 
     } 

     STATES.keys.each do |s| 
     define_method "#{s}?" do 
      self.state == s.to_s 
     end 
     end 
    end 
+0

這看起來很不錯。 「guard: - >(draw)」 是什麼意思? 之前沒有在散列中看到過這個。 – Randomtheories

+0

- >()只是lambdas的簡寫符號。您的視圖可以在所有狀態下使用所有這種方法來查看它可以合法地轉換到哪個狀態。 –