百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
E

enumerate_it

> 后端框架
开源

Ruby 的枚举,具有一些神奇的功能!

351 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

Ruby 的枚举,具有一些神奇的功能!

EnumerateIt

Enumerations for Ruby with some magic powers! EnumerateIt helps you declare and use enumerations in a very simple and flexible way.

Why would I want a gem if Rails already has native enumeration support?

Firstly, although EnumerateIt works well with Rails, it isn't required! This means you can add it to any Ruby project! Secondly, you can define your enumerations in classes, allowing you to add behavior and reuse them!

At a glance:

ruby
class RelationshipStatus  true
person.ever_married? #=> true
person.relationship_status_humanize #=> 'Married'
Person.married.to_sql #=> SELECT "people".* FROM "people" WHERE "people"."relationship_status" = "married"
RelationshipStatus.to_a #=> [['Divorced', 'divorced'], ['Married', 'married'], ['Single', 'single']]

Table of Contents

  • Installation
  • Using with Rails
  • Creating enumerations
    • Sorting enumerations
  • Using enumerations
  • FAQ
    • Why define enumerations outside the class that uses them?
    • Can I use enumerate_it gem without Rails?
    • What versions of Ruby and Rails are supported?
    • Can I set a value to always be at the end of a sorted list?
  • I18n
    • Translate a namespaced enumeration
  • Handling a legacy database
  • Changelog
  • Note on Patches/Pull Requests
  • Copyright

Installation

bash
gem install enumerate_it

Using with Rails

Add the gem to your Gemfile:

ruby
gem 'enumerate_it'

You can use a Rails generator to create both an enumeration and its locale file:

bash
rails generate enumerate_it:enum --help

Creating enumerations

Enumerations are created as classes and should be placed inside the app/enumerations folder.

You can pass an array of symbols, where each symbol's value will be its stringified version:

ruby
class RelationshipStatus  'single'

  RelationshipStatus::MARRIED
  #=> 'married'
  • A list of all enumeration codes:

    ruby
    RelationshipStatus.list
    #=> ['divorced', 'married', 'single']
  • A JSON representation:

    ruby
    RelationshipStatus.to_json
    #=> "[{\"value\":\"divorced\",\"label\":\"Divorced\"},{\"value\":\"married\", ...
  • An array of options for Rails helpers, such as select, select_tag, etc.:

    ruby
    RelationshipStatus.to_a
    #=> [['Divorced', 'divorced'], ['Married', 'married'], ['Single', 'single']]
  • You can retrieve a list with values for a group of enumeration constants.

    ruby
    RelationshipStatus.values_for %w(MARRIED SINGLE)
    #=> ['married', 'single']
  • You can retrieve the value for a specific enumeration constant:

    ruby
    RelationshipStatus.value_for('MARRIED')
    #=> 'married'
  • You can retrieve the symbol used to declare a specific enumeration value:

    ruby
    RelationshipStatus.key_for(RelationshipStatus::MARRIED)
    #=> :married
  • You can iterate over the list of the enumeration's values:

    ruby
    RelationshipStatus.each_value { |value| ... }
  • You can iterate over the list of the enumeration's translations:

    ruby
    RelationshipStatus.each_translation { |translation| ... }
  • You can also retrieve all the translations of the enumeration:

    ruby
    RelationshipStatus.translations
  • You can ask for the enumeration's length:

    ruby
    RelationshipStatus.length
    #=> 3

Sorting enumerations

When calling methods like to_a, to_json and list, values are sorted in the order they were passed to associate_values, by default.

You can override this with the sort_by class method:

ruby
class RelationshipStatus  [!NOTE]
> If the enumeration class name differs from the attribute name, use the `with` option:
>
> ```ruby
> has_enumeration_for :relationship_status, with: RelationshipStatus
> ```

This will create:

- A "humanized" version of the hash's key to humanize the attribute's value:

  ```ruby
  p = Person.new
  p.relationship_status = RelationshipStatus::DIVORCED
  p.relationship_status_humanize
  #=> 'Divorced'
  • A translation for your options, if you include a locale to represent it (see more in the I18n section).

    ruby
    p = Person.new
    p.relationship_status = RelationshipStatus::DIVORCED
    p.relationship_status_humanize
    #=> 'Divorciado' # with a pt-BR locale loaded
  • The associated enumerations, which can be retrieved with the enumerations class method:

    ruby
    Person.enumerations
    #=> { relationship_status: RelationshipStatus }
  • A helper method for each enumeration option, if you pass the create_helpers option as true:

    ruby
    class Person  true
    
    p.divorced?
    #=> false

    It's also possible to "namespace" the created helper methods, passing a hash to the create_helpers option. This can be useful when two or more of the enumerations used share the same constants:

    ruby
    class Person  true
    
    p.relationship_status_divorced?
    #=> false

    You can define polymorphic behavior for the enumeration values, so you can define a class for each of them:

    ruby
    class RelationshipStatus  'At home with the kids'
    
    p.relationship_status = RelationshipStatus::SINGLE
    p.relationship_status_object.saturday_night
    #=> 'Party hard!'

    You can also change the suffix _object, using the suffix option:

    ruby
    class Person  true

    [!IMPORTANT] On ActiveRecord objects, mutator methods like married! call save! immediately, running callbacks and raising on validation failure. They are not pure setters.

    You can also define custom helper methods on the enumeration class using a custom_helpers block:

    ruby
    class RelationshipStatus  true
    RelationshipStatus.ever_married?(RelationshipStatus::DIVORCED) #=> true
    RelationshipStatus.ever_married?(RelationshipStatus::SINGLE)   #=> false

    When create_helpers: true is used, they also become instance methods on the model:

    ruby
    class Person  true

    The prefix option also applies to custom helpers:

    ruby
    class Person  true

    Custom helper methods return nil when the attribute is nil. If a method name collides with an already-defined class method on the enumeration, an ArgumentError is raised at load time.

  • A scope method for each enumeration option if you pass the create_scopes option as true:

    ruby
    class Person  SELECT "people".* FROM "people" WHERE "people"."relationship_status" = "married"

    The :create_scopes also accepts prefix option.

    ruby
    class Person  false
    p.errors[:relationship_status]
    #=> 'is not included in the list'
  • A presence validation (if your class can manage validations and responds to validates_presence_of and you pass the required options as true):

    ruby
    class Person  false
    p.errors[:relationship_status]
    #=> "can't be blank"

    If you pass the skip_validation option as true, it will not create any validations:

    ruby
    class Person  true
…

yaml

Your locale file

pt-BR: enumerations: relationship_status: married: Casado


```ruby
class RelationshipStatus  'Casado'

p.relationship_status = RelationshipStatus::SINGLE
p.relationship_status_humanize # Key missing, falls back to the humanized name
#=> 'Single'

You can also translate specific values:

ruby
status = RelationshipStatus::MARRIED
RelationshipStatus.t(status)
#=> 'Casado'

Translate a namespaced enumeration

In order to translate an enumeration in a specific namespace (say Design::Color), use the following structure:

yaml
pt-BR:
  enumerations:
    "design/color":
      blue: Azul
      red: Vermelho

Handling a legacy database

EnumerateIt can help you build a Rails application around a legacy database which was filled with those small and unchangeable tables used to create foreign key constraints everywhere, like the following example:

sql
Table "public.relationship_status"

  Column     |     Type      | Modifiers
-------------+---------------+-----------
 code        | character(1)  | not null
 description | character(11) |

Indexes:
  "relationship_status_pkey" PRIMARY KEY, btree (code)

SELECT * FROM relationship_status;

code |  description
---- +--------------
1    | Single
2    | Married
3    | Divorced

You might also have something like a users table with a relationship_status column and a foreign key pointing to the relationship_status table.

While this is a good thing from the database normalization perspective, managing these values in tests is very hard. Doing database joins just to get the description of some value is absurd. And, more than this, referencing them in the code using magic numbers was terrible and meaningless: what does it mean when we say that someone or something is 2?

To solve this, you can pass a hash to your enumeration values:

ruby
class RelationshipStatus  2

You can also sort it by its value using sort_by :value.

Changelog

Changes follows the Semantic Versioning specification and you can see them on the releases page.

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so we don't break it in a future version unintentionally.
  • [Optional] Run the tests against a specific Gemfile: bundle exec appraisal rails_8.1 rake spec.
  • Run the tests against all supported versions: bundle exec rake
  • Commit, but please do not mess with Rakefile, version, or history.
  • Send a Pull Request. Bonus points for topic branches.

Copyright

Copyright (c) 2010-2026 Cássio Marques and Lucas Caton. See LICENSE file for details.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyenumerationrailsrubyruby-enumerations

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架