String enums for Rails
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
lib
test
.gitignore
CHANGELOG.md
Gemfile
LICENSE.txt
README.md
Rakefile
str_enum.gemspec

README.md

str_enum

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

String enums for Rails!! 🎉

  • scopes
  • validations
  • accessor methods

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

Validations

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

Accessor 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,
    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?

History

View the changelog

Contributing

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