Skip to content

gregblass/str_enum

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

44 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

str_enum

Don’t like storing enums as integers in your database? Introducing...

String enums for Rails!! 🎉

  • scopes
  • validations
  • accessor methods
  • update methods

Build Status

Getting Started

Add this line to your application’s Gemfile:

gem 'str_enum'

Add a string column to your model.

add_column :users, :status, :string

And use:

class User < ActiveRecord::Base
  str_enum :status, [:active, :archived]
end

The first value will be the initial value. This gives you:

Scopes

User.active
User.archived

And negative scopes

User.not_active
User.not_archived

Validations

user = User.new(status: "unknown")
user.valid? # false

Accessor Methods

user.active?
user.archived?

Update Methods

user.active!
user.archived!

Forms

<%= f.select :status, User.statuses.map { |s| [s.titleize, s] } %>

Options

Choose which features you want with:

class User < ActiveRecord::Base
  str_enum :status, [:active, :archived],
    scopes: false,
    validate: false,
    accessor_methods: false,
    update_methods: false,
    default: nil
end

Prevent method name collisions with the prefix and suffix options.

class User < ActiveRecord::Base
  str_enum :address_status, [:active, :archived], suffix: :address
end

# scopes
User.active_address
User.archived_address

# accessor methods
user.active_address?
user.archived_address?

# update methods
user.active_address!
user.archived_address!

History

View the changelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

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

About

String enums for Rails

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby 100.0%