【问题标题】:Enums in Rails without ActiveRecord没有 ActiveRecord 的 Rails 中的枚举
【发布时间】:2014-11-07 14:14:20
【问题描述】:

我想在 MongoMapper 和 rails 4 中使用枚举。 我知道有一些宝石 (enumerize) 添加了这种行为,但对于一个小功能来说似乎需要添加很多东西。

为 ActiveModel 类创建枚举的最简单方法是什么?

【问题讨论】:

    标签: ruby-on-rails-4 enums activemodel


    【解决方案1】:

    使用 getter、setter 和常量数组可以快速实现:

    class Subscription
      include MongoMapper::Document
      ...
    
      key :status, Integer
    
      STATE = [:queued, :submitted, :processing, :payment_received, :fully_paid, :error]
    
      def status=(str)
        @status = STATE.index(str)
      end
    
      def status
        STATE[@status]
      end
    end
    

    您甚至可以为常见查询添加检查,例如,错误状态可能需要比其他人更频繁地检查,您可以跳过符号 > 整数转换:

    def errors?
      @status == 5
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多