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

标签 ruby-on-rails ruby constants enumeration

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

最佳答案

您可以为此目的使用数组或散列(在您的 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']

关于ruby-on-rails - 使用 Rails 时,在 Ruby 中处理常量的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/265725/

相关文章:

ruby - 为什么 delete 返回的是被删除的元素而不是新数组?

c++ - 关于通过 const 指针/const 引用传递的 2 个快速问题

ruby-on-rails - Rails 中的常量值

ruby-on-rails - 使用 CSS 为 erb 中的 Ruby 对象设置样式

ruby-on-rails - Rspec 在 rails 上失败

html - 表格中可点击行的错误 (Rails 4)

ruby - 帮助重构 Ruby 哈希切片和切 block

c++ - 混合 const 和非常量传递引用的参数顺序

c++ - 访问对象列表中的非常量成员

ruby-on-rails - Rails 5 的 Omniauth-twitter 停止工作! OAuth::Unauthorized 403 Forbidden