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

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

问题描述:

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

I have some constants that represent the valid options in one of my model's fields. What's the best way to handle these constants in Ruby?

您可以为此目的使用数组或哈希(在您的环境中) .rb):

You can use an array or hash for this purpose (in your environment.rb):

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

或一个枚举类,它允许您枚举常量和键用于关联它们:

or alternatively an enumeration class, which allows you to enumerate over your constants as well as the keys used to associate them:

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']