Magic Numbers is a simple Rails plugin which brings transparent enums and sets (bitfields) to AR objects. It doesn’t require native database support for enums or sets, instead of this it stores values as plain integers.
Magic Numbers usage is simple:
class User < ActiveRecord::Base enum_attribute :state, :values => [:passive, :active, :deleted] bitfield_attribute :roles, :values => [:user, :moderator, :administrator] end
After this you can set user’s state with symbols or strings:
@user.state # => nil @user.state = :active @user.state = 'deleted' @user.state # => :deleted @user[:state] # In such way you can get value which will actually be stored in DB # => 2
And you can work with bitfield attributes as regular arrays:
@user.roles # => nil @user.roles = [:user] @user.roles # => [:user] @user.roles <<= :moderator @user.roles # => [:user, :moderator] @user[:roles] # => 3
Sometimes (for example, in search queries) you need to get magic numbers which corresponds to specific values. You can use magic_number_for
method for this, i.e.:
deleted_users = @user.find(:all, :conditions => { :state => User.magic_number_for(:state, :deleted) })
Also you can get entire magic number attribute options hash by it’s name:
User.magic_number_attribute_options(:state) # => { :type => :enum, :values => [:passive, :active, :deleted], :stringified_values => ["passive", "active", "deleted"] }
Magic-numbered columns will handle all incorrect (unspecified) values as nil
:
@user.state = 'incorrect state value' @user.state # => nil @user.roles = [:user, nil, :dancer] # NB :dancer is an incorrect role @user.roles # => [:user]
Copyright © 2009 Mikhail Lapshin (sotakone at sotakone dot com), released under the MIT license.
Feel free to mail me with any questions regarding this plugin.