Ruby中的枚举 [英] Enumeration in Ruby on rails
问题描述
我是一个C#程序员,我正在寻找在轨道上的红宝石。但是我有一些麻烦可能是用心灵设置或某些东西。
i am a C# programmer and i am looking in to ruby on rails. but i am having some trouble probably with the mind set or something.
我有一个对象投票,该对象可以是Pro,Neutral或con。
I have an object Vote, that object can be Pro, Neutral or con.
我将正常使投票对象有一些这样的东西这样的
I would normaly make the vote object have a field some thing like this
private VoteEnum voteEnum = VoteEnum.Neutral
我可以在ruby中填充这个。
how on earth can i acomplish this in ruby.
我发现了一些例子:
def MyClass < ActiveRecord::Base
ACTIVE_STATUS = "active"
INACTIVE_STATUS = "inactive"
PENDING_STATUS = "pending"
end
然后,当使用另一个类的模型时,我引用常量
Then, when using the model from another class, I reference the constants
@model.status = MyClass::ACTIVE_STATUS
@model.save
对我来说似乎是正确的,但我的主要问题是我如何告诉模型,状态是枚举或constain的类型。
This seems correct to me but my main question is how do i tell the model that status is the type of enum or constain..
我希望你明白我的问题,希望你可以帮我弄清楚这一点。
I hope you understand my question, and hope you can help me get my mind wrapped around this.
推荐答案
Ruby不像C#那样严格类型化。但是您可以使用验证来检查状态:
Ruby isn't strictly-typed like C#. But you can use validations to check what's in the status:
def MyClass < ActiveRecord::Base
ACTIVE_STATUS = "active"
INACTIVE_STATUS = "inactive"
PENDING_STATUS = "pending"
NUMERICAL_STATUS = 500 # this is weird but okay
ALL_STATUSES = [ACTIVE_STATUS, INACTIVE_STATUS, PENDING_STATUS, NUMERICAL_STATUS]
validates_inclusion_of :status, :in => ALL_STATUSES
end
这篇关于Ruby中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!