簡體   English   中英

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

[英]What is the best way to handle constants in Ruby when using Rails?

我有一些常量代表我的一個模型字段中的有效選項。 在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']

我把它們直接放在模型類中,如下所示:

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

然后,當使用來自另一個類的模型時,我引用了常量

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

如果它是驅動模型行為,那么常量應該是模型的一部分:

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插件之類的東西。

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

有關詳細的說明 ,請參閱其文檔

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


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

您還可以使用模塊將常量分組到主題中 -

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

然后有,

> Runner::RUN_TYPES::SYNC
 => 0
> Runner::RUN_TYPES::ASYNC
 => 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM