Skip to content

ActiveRecord plugin for transparent enum and bitfield model attributes

License

Notifications You must be signed in to change notification settings

mlapshin/magic_numbers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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, :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

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.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"] }

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.

About

ActiveRecord plugin for transparent enum and bitfield model attributes

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages