Enumeration in Ruby on rails
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.
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
how on earth can i acomplish this in ruby.
i have found some examples like:
def MyClass < ActiveRecord::Base
ACTIVE_STATUS = "active"
INAC开发者_如何学CTIVE_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
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 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
Normally, if it is just an enum as used in C++ or C#, i would translate that as follows:
class VoteStatus
ACTIVE_STATUS=0
INACTIVE_STATUS=1
PENDING_STATUS=2
end
so you store an integer in your database, and the meaning is clear in your code.
However, i would suggest using a simple domain table for this. That way you define and can maintain the possible statuses inside your database, you define an id, name and description and suddenly your statuses are self-documented and names and descriptions can be shown to the user as well (hoping you don't need translations :).
精彩评论