Don’t like storing enums as integers in your database? Introducing...
String enums for Rails!! 🎉
- scopes
- validations
- accessor methods
- update methods
Add this line to your application’s Gemfile:
gem"str_enum"Add a string column to your model.
add_column:users,:status,:stringAnd use:
classUser < ActiveRecord::Basestr_enum:status,[:active,:archived]endThe first value will be the initial value. This gives you:
User.activeUser.archivedAnd negative scopes
User.not_activeUser.not_archiveduser=User.new(status: "unknown")user.valid?# falseuser.active?user.archived?user.active!user.archived!<%= f.select :status, User.statuses.map { |s| [s.titleize, s] } %>Choose which features you want with (default values shown):
classUser < ActiveRecord::Basestr_enum:status,[:active,:archived],accessor_methods: true,allow_nil: false,default: true,prefix: false,scopes: true,suffix: false,update_methods: true,validate: trueendPrevent method name collisions with the prefix and suffix options.
classUser < ActiveRecord::Basestr_enum:address_status,[:active,:archived],suffix: :addressend# scopesUser.active_addressUser.archived_address# accessor methodsuser.active_address?user.archived_address?# update methodsuser.active_address!user.archived_address!View the changelog
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- Report bugs
- Fix bugs and submit pull requests
- Write, clarify, or fix documentation
- Suggest or add new features
To get started with development and testing:
git clone https://github.com/ankane/str_enum.git
cd str_enum
bundle install
bundle exec rake test