Project

enumize

0.01
No release in over 3 years
Low commit activity in last 3 years
Extend ActiveRecord::Enum for add more helpful methods
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Development

>= 0

Runtime

>= 5.0.0
 Project Readme

Enumize

build

Extend ActiveRecord::Enum for add more helpful methods, from rails/rails#36503.

🚨 This Gem does not change the way you use ActiveRecord::Enum, just adds method extensions.

中文介绍与使用说明

Usage

class Book
  enum status: %i[draft published archived]
end

Now we have status_name, status_color, status_value and Book.status_options methods:

  • #{attribute}_name - return I18n name for display.
  • #{attribute}_color - return color for enum value from I18n file.
  • #{attribute}_value - return raw value for enum, Now we don't need use Book.statuses[@book.status].
  • Book.#{attribute}_options - return a array list for select tag options, <%= f.select :status, Book.status_options %>.

Write I18n:

en:
  activerecord:
    enums:
      book:
        status:
          draft: Drafting
          published: Published
          archived: Archived
        status_color:
          draft: '#999999'
          published: 'green'
          archived: 'red'

zh-CN:
  activerecord:
    enums:
      book:
        status:
          draft: '草稿'
          published: '已发布'
          archived: '归档'

use the methods:

irb> @book = Book.new(status: :draft)
irb> @book.status_value
0
irb> @book.status_name
"草稿"
irb> @book.status_color
"#999999"
# You can still use the original methods from ActiveRecord::Enum
irb> @book.status
"draft"
irb> @book.draft?
true
irb> @book.published!
irb> @book.published?
true
irb> @book.status
"published"

For _options methods for select helper:

<% form_for(@book) do |f| %>
  <%= f.text_field :name %>
  <%= f.select :status, Book.status_options %>
  <%= f.submit %>
<% end >

Installation

Add this line to your application's Gemfile:

gem 'enumize'

And then execute:

$ bundle

Configure the I18n fallbacks for color method

You can write color config in en.yml once for all locales, so follow the I18n fallback, the others locale will use color value from en:

config/application.rb

module Dummy
  class Application < Rails::Application
    # Add to tell I18n fallback translate to en
    config.i18n.available_locales = ["en", "zh-CN"]
    config.i18n.fallbacks = true
  end
end

License

The gem is available as open source under the terms of the MIT License.