Qual è il modo migliore per gestire le costanti in Ruby quando si usa Rails?
-
06-07-2019 - |
Domanda
Ho alcune costanti che rappresentano le opzioni valide in uno dei campi del mio modello. Qual è il modo migliore per gestire queste costanti in Ruby?
Soluzione
È possibile utilizzare un array o un hash per questo scopo (nel proprio ambiente.rb):
OPTIONS = ['one', 'two', 'three']
OPTIONS = {:one => 1, :two => 2, :three => 3}
o in alternativa una classe di enumerazione, che ti consente di enumerare le tue costanti e le chiavi utilizzate per associarle:
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
da cui è possibile derivare:
class Values < Enumeration
self.add_item(:RED, '#f00')
self.add_item(:GREEN, '#0f0')
self.add_item(:BLUE, '#00f')
end
e usalo in questo modo:
Values::RED => '#f00'
Values::GREEN => '#0f0'
Values::BLUE => '#00f'
Values.keys => [:RED, :GREEN, :BLUE]
Values.values => ['#f00', '#0f0', '#00f']
Altri suggerimenti
Li inserisco direttamente nella classe del modello, in questo modo:
class MyClass < ActiveRecord::Base
ACTIVE_STATUS = "active"
INACTIVE_STATUS = "inactive"
PENDING_STATUS = "pending"
end
Quindi, quando utilizzo il modello di un'altra classe, faccio riferimento alle costanti
@model.status = MyClass::ACTIVE_STATUS
@model.save
Se sta guidando il comportamento del modello, le costanti dovrebbero far parte del modello:
class Model < ActiveRecord::Base
ONE = 1
TWO = 2
validates_inclusion_of :value, :in => [ONE, TWO]
end
Questo ti permetterà di usare la funzionalità Rails integrata:
>> m=Model.new
=> #<Model id: nil, value: nil, created_at: nil, updated_at: nil>
>> m.valid?
=> false
>> m.value = 1
=> 1
>> m.valid?
=> true
In alternativa, se il tuo database supporta le enumerazioni, puoi usare qualcosa come Enum Column plugin.
Rails 4.1 ha aggiunto supporto per enumerazioni ActiveRecord .
Dichiara un attributo enum in cui i valori sono associati a numeri interi nel database, ma possono essere interrogati per nome.
class Conversation < ActiveRecord::Base
enum status: [ :active, :archived ]
end
conversation.archived!
conversation.active? # => false
conversation.status # => "archived"
Conversation.archived # => Relation for all archived Conversations
Vedi la sua documentazione per una descrizione dettagliata.
Puoi anche usarlo all'interno del tuo modello all'interno di un hash come questo:
class MyModel
SOME_ATTR_OPTIONS = {
:first_option => 1,
:second_option => 2,
:third_option => 3
}
end
E usalo in questo modo:
if x == MyModel::SOME_ATTR_OPTIONS[:first_option]
do this
end
Puoi anche raggruppare le costanti in soggetti, usando un modulo -
class Runner < ApplicationRecord
module RUN_TYPES
SYNC = 0
ASYNC = 1
end
end
E poi,
> Runner::RUN_TYPES::SYNC
=> 0
> Runner::RUN_TYPES::ASYNC
=> 1