使用Rails时在Ruby中处理常量的最佳方法是什么?

时间:2008-11-05 16:31:23

标签: ruby-on-rails ruby constants enumeration

我有一些常量代表我的某个模型字段中的有效选项。在Ruby中处理这些常量的最佳方法是什么?

6 个答案:

答案 0 :(得分:40)

您可以为此目的使用数组或散列(在environment.rb中):

OPTIONS = ['one', 'two', 'three']
OPTIONS = {:one => 1, :two => 2, :three => 3}

或者是枚举类,它允许您枚举常量以及用于关联它们的键:

class Enumeration
  def Enumeration.add_item(key,value)
    @hash ||= {}
    @hash[key]=value
  end

  def Enumeration.const_missing(key)
    @hash[key]
  end   

  def Enumeration.each
    @hash.each {|key,value| yield(key,value)}
  end

  def Enumeration.values
    @hash.values || []
  end

  def Enumeration.keys
    @hash.keys || []
  end

  def Enumeration.[](key)
    @hash[key]
  end
end

然后你可以从

获得
class Values < Enumeration
  self.add_item(:RED, '#f00')
  self.add_item(:GREEN, '#0f0')
  self.add_item(:BLUE, '#00f')
end

并使用如下:

Values::RED    => '#f00'
Values::GREEN  => '#0f0'
Values::BLUE   => '#00f'

Values.keys    => [:RED, :GREEN, :BLUE]
Values.values  => ['#f00', '#0f0', '#00f']

答案 1 :(得分:11)

我将它们直接放在模型类中,如下所示:

class MyClass < ActiveRecord::Base
  ACTIVE_STATUS = "active"
  INACTIVE_STATUS = "inactive"
  PENDING_STATUS = "pending"
end

然后,当使用另一个类的模型时,我引用了常量

@model.status = MyClass::ACTIVE_STATUS
@model.save

答案 2 :(得分:9)

如果它是驱动模型行为,那么常量应该是模型的一部分:

class Model < ActiveRecord::Base
  ONE = 1
  TWO = 2

  validates_inclusion_of :value, :in => [ONE, TWO]
end

这将允许您使用内置的Rails功能:

>> m=Model.new
=> #<Model id: nil, value: nil, created_at: nil, updated_at: nil>
>> m.valid?
=> false
>> m.value = 1
=> 1
>> m.valid?
=> true

或者,如果您的数据库支持枚举,那么您可以使用类似Enum Column插件的内容。

答案 3 :(得分:7)

Rails 4.1添加了support for ActiveRecord enums

声明一个枚举属性,其中值映射到数据库中的整数,但可以按名称查询。

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

conversation.archived!
conversation.active? # => false
conversation.status  # => "archived"

Conversation.archived # => Relation for all archived Conversations

有关详细说明,请参阅its documentation

答案 4 :(得分:5)

您也可以在模型中使用它,如下所示:


class MyModel

  SOME_ATTR_OPTIONS = {
    :first_option => 1,
    :second_option => 2, 
    :third_option => 3
  }
end

并像这样使用它:



if x == MyModel::SOME_ATTR_OPTIONS[:first_option]
  do this
end

答案 5 :(得分:0)

您还可以使用模块< - p>将常量分组到主题中

class Runner < ApplicationRecord
    module RUN_TYPES
        SYNC = 0
        ASYNC = 1
    end
end

然后,

> Runner::RUN_TYPES::SYNC
 => 0
> Runner::RUN_TYPES::ASYNC
 => 1
相关问题