我需要创建一个枚举,需要从querystring中的值初始化该枚举。
我有什么和我需要做什么的例子:
class UserType
NONE = 0
MEMBER = 1
ADMIN = 2
SUPER = 3
end
现在,在我的查询字符串中,我将有:
/users/load_by_type?type=2
现在,在我的控制器中,我将从querystring中获得值2,然后我需要一个值为"MEMBER"的UserType对象。
我该怎么做?
如果我的类不是一个很好的枚举破解,请建议。
这样的东西怎么样。
require 'active_record'
# set up db
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
# define schema
ActiveRecord::Schema.define do
suppress_messages do
create_table :users do |t|
t.string :name
t.string :role
end
end
end
# define class
class User < ActiveRecord::Base
Roles = %w[none member admin super].map(&:freeze)
validates_inclusion_of :role, in: Roles
end
# specification
describe User do
before { User.delete_all }
let(:valid_role) { User::Roles.first }
let(:invalid_role) { valid_role.reverse }
it 'is valid if its role is in the Roles list' do
User.new.should_not be_valid
User.new(role: valid_role).should be_valid
User.new(role: invalid_role).should_not be_valid
end
let(:role) { User::Roles.first }
let(:other_role) { User::Roles.last }
it 'can find users by role' do
user_with_role = User.create! role: role
user_with_other_role = User.create! role: other_role
User.find_all_by_role(role).should == [user_with_role]
end
end
它确实有使用整个字符串(255个字符)作为枚举方法的缺点,但它也有可读性和易用性的优点(它可能是"/users/load_by_role?role=admin")。此外,如果在某个时候它的成本太高,那么应该很容易更新为使用小整数。
我想我宁愿使用哈希来处理这类事情,但只是为了好玩:
class Foo
BAR = 1
STAN = 2
class << self
def [](digit)
constants.find { |const| const_get(const) == digit }
end
end
end
puts Foo[1] # BAR
puts Foo[2] # STAN