Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

79 lines (52 sloc) 2.005 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.

Example

Magic Numbers usage is simple:

class User < ActiveRecord::Base
  enum_attribute     :state, %w(passive active deleted)
  bitfield_attribute :roles, %w(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

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:

User.magic_number_attribute_options(:state)
# => { :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'
@user.state
# => nil

@user.roles = [:user, nil, :dancer] # NB :dancer is an incorrect role
@user.roles
# => [:user]

Copyrights

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.

Jump to Line
Something went wrong with that request. Please try again.