Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
79 lines (52 sloc) 1.96 KB

Magic Numbers plugin

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, %w(passive active deleted)
  bitfield_attribute :roles, %w(user moderator administrator)

After this you can set user's state with symbols or strings:

# => nil

@user.state = :active
@user.state = 'deleted'

# => :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:

# => nil

@user.roles = [:user]
# => [:user]

@user.roles <<= :moderator
# => [:user, :moderator]

# => 3

Getting magic numbers for specified values

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.where(:state => User.magic_number_for(:state, :deleted))

Also you can get entire magic number attribute options hash by it's name:

# => { :type               => :enum,
       :values             => [:passive,  :active,  :deleted],
       :stringified_values => ["passive", "active", "deleted"] }

Handling of incorrect values

Magic-numbered columns will handle all incorrect (unspecified) values as nil:

@user.state = 'incorrect state value'
# => nil

@user.roles = [:user, nil, :dancer] # NB :dancer is an incorrect role
# => [: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.