处理Rails中的多个状态

时间:2015-11-03 15:14:49

标签: ruby-on-rails design-patterns state

目前,我试图找出如何在我的Rails应用程序中处理状态的最佳方法。

我有一个模型(Draws),可以处理三维中的多个状态。

  • 有效/无效
  • 开始/正在运行/已结束
  • not_full / full

我需要处理五种状态:

  • 不活跃&所有其他州
  • 活跃& not_started& not_full
  • 活跃&跑步& not_full
  • 活跃&跑步&完整
  • 活跃&结束&全

有人可以指出我正确使用宝石或阅读文章以了解如何处理Rails中的状态吗? 这是将不同属性结合到状态的正确方法吗? 我是否必须单独定义每个过渡?

1 个答案:

答案 0 :(得分:1)

我通常不会使用gems来处理状态机,因为我通常需要微调通常超出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
相关问题