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

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

Miles asked 2020-08-01T15:19:01Z
6个解决方案
40 votes

您可以为此目的使用数组或哈希(在您的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']
Codebeef answered 2020-08-01T15:19:30Z
11 votes

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

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

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

@model.status = MyClass::ACTIVE_STATUS
@model.save
Micah answered 2020-08-01T15:19:54Z
9 votes

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

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

或者,如果您的数据库支持枚举,则可以使用“枚举列”插件之类的东西。

Dave answered 2020-08-01T15:20:23Z
7 votes

Rails 4.1添加了对ActiveRecord枚举的支持。

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

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

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

Conversation.archived # => Relation for all archived Conversations

请参阅其文档以获取详细的内容。

Simone Carletti answered 2020-08-01T15:20:52Z
5 votes

您还可以在模型中的哈希内使用它,如下所示:


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

Dema answered 2020-08-01T15:21:16Z
0 votes

您还可以使用模块将常量分组为主题-

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

然后有

> Runner::RUN_TYPES::SYNC
 => 0
> Runner::RUN_TYPES::ASYNC
 => 1
Ady Rosen answered 2020-08-01T15:21:40Z
translate from https://stackoverflow.com:/questions/265725/what-is-the-best-way-to-handle-constants-in-ruby-when-using-rails