{"id":13462896,"url":"https://github.com/lwe/simple_enum","last_synced_at":"2025-03-25T06:31:22.333Z","repository":{"id":567461,"uuid":"198824","full_name":"lwe/simple_enum","owner":"lwe","description":"Simple enum-like field support for ActiveModel (including validations and i18n)","archived":false,"fork":false,"pushed_at":"2023-12-07T17:06:20.000Z","size":469,"stargazers_count":414,"open_issues_count":14,"forks_count":61,"subscribers_count":12,"default_branch":"master","last_synced_at":"2025-03-14T09:06:32.127Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lwe.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2009-05-12T13:12:52.000Z","updated_at":"2025-01-20T07:21:02.000Z","dependencies_parsed_at":"2024-06-18T13:53:54.204Z","dependency_job_id":null,"html_url":"https://github.com/lwe/simple_enum","commit_stats":{"total_commits":438,"total_committers":36,"mean_commits":"12.166666666666666","dds":0.1735159817351598,"last_synced_commit":"1fbfaeff50c61c023130451a9418fce97a7ec5bf"},"previous_names":[],"tags_count":32,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lwe%2Fsimple_enum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lwe%2Fsimple_enum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lwe%2Fsimple_enum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lwe%2Fsimple_enum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lwe","download_url":"https://codeload.github.com/lwe/simple_enum/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245413741,"owners_count":20611353,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T13:00:40.531Z","updated_at":"2025-03-25T06:31:22.063Z","avatar_url":"https://github.com/lwe.png","language":"Ruby","readme":"SimpleEnum\n==========\n\n[![Gem Version](https://badge.fury.io/rb/simple_enum.svg)](https://badge.fury.io/rb/simple_enum)\n[![Build Status](https://travis-ci.org/lwe/simple_enum.svg)](https://travis-ci.org/lwe/simple_enum)\n[![Code Climate](https://codeclimate.com/github/lwe/simple_enum.svg)](https://codeclimate.com/github/lwe/simple_enum)\n\nUnobtrusive enum-like fields for ActiveRecord and Ruby, brings enums functionality\nto ActiveRecord and Mongoid models (built for Rails 4+).\n\nSince version 2.0, simple_enum is no longer compatible with Rails 3.x or Ruby 1.8,\nuse version 1.6 instead: https://github.com/lwe/simple_enum/tree/legacy-1.x\n\n*Note*: a recent search on github for `enum` turned out, that there are many,\nmany similar solutions. In fact starting with Rails 4.1, there's `ActiveRecord::Enum`\nwhich provides **some** of the functionality, but is IMHO pretty limited and too\nstrict in the defaults it provides.\n\nActiveRecord Quick start\n------------------------\n\nAdd this to a model:\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  as_enum :gender, female: 1, male: 0\nend\n```\n\nThen create the required `gender_cd` column using migrations:\n\n```ruby\nclass AddGenderColumnToUser \u003c ActiveRecord::Migration\n  def self.up\n    add_column :users, :gender_cd, :integer\n  end\n\n  def self.down\n    remove_column :users, :gender_cd\n  end\nend\n```\n\nMongoid Quick start\n-------------------\n\nDue to the dependency on ActiveModel 4.x, the Mongoid integration is only\navailable for mongoid 4.0.0 (which is at beta1 at the moment). If you intend\nto use simple_enum with another version of mongoid, use version 1.6 instead.\n\nLoad mongoid support in the `Gemfile`:\n\n```ruby\ngem 'simple_enum', '~\u003e 2.3.0' , require: 'simple_enum/mongoid'\n```\n\nAdd this to a model:\n\n```ruby\nclass User\n  include Mongoid::Document\n  include SimpleEnum::Mongoid\n\n  as_enum :gender, female: 1, male: 0\nend\n```\n\nThe primary difference between AR and mongoid is, that additionaly a field is\nadded to mongoid automatically, the field can be customized by setting `field:`\noption, or disabled by setting `field: false`.\n\nWorking with enums\n------------------\n\nNow it's possible to pull some neat tricks on the new column, yet the original\ndb column (`gender_cd`) is still intact and not touched by anything.\n\n```ruby\njane = User.new\njane.gender = :female\njane.female?   # =\u003e true\njane.male?     # =\u003e false\njane.gender    # =\u003e :female\njane.gender_cd # =\u003e 1\n```\n\nEasily switch to another value using the bang methods, this does not save\nthe record, only switch the value.\n\n```ruby\njoe = User.new\njoe.male!     # =\u003e :male\njoe.gender    # =\u003e :male\njoe.gender_cd # =\u003e 0\n```\n\nAccessing actual enum values is possible at the class level:\n\n```ruby\nUser.genders                            # =\u003e #\u003cSimpleEnum::Enum:0x0....\u003e\nUser.genders[:male]                     # =\u003e 0\nUser.genders.values_at(:male, :female)  # =\u003e [0, 1] (since 2.1.0)\nUser.females                            # =\u003e #\u003cActiveRecord::Relation:0x0.....\u003e (WHERE gender_cd = 1)\n```\n\nBy default, scope names are generated as pluralized forms of the defined enum values e.g.\n\n```ruby\nclass Booking \u003c ActiveRecord::Base\n  as_enum :status, %i{active cancelled pending}\nend\n```\n\nwould generate the following:\n```ruby\nBooking.actives     # =\u003e #\u003cActiveRecord::Relation:0x0.....\u003e (WHERE status_cd = 1)\nBooking.cancelleds  # =\u003e #\u003cActiveRecord::Relation:0x0.....\u003e (WHERE status_cd = 2)\nBooking.pendings    # =\u003e #\u003cActiveRecord::Relation:0x0.....\u003e (WHERE status_cd = 3)\n```\n\nBy setting `pluralize_scopes: false` will not generate pluralized versions of scopes e.g.\n\n```ruby\nclass Booking \u003c ActiveRecord::Base\n  as_enum :status, %i{active cancelled pending}, pluralize_scopes: false\nend\n```\n\nwould generate the following:\n```ruby\nBooking.active     # =\u003e #\u003cActiveRecord::Relation:0x0.....\u003e (WHERE status_cd = 1)\nBooking.cancelled  # =\u003e #\u003cActiveRecord::Relation:0x0.....\u003e (WHERE status_cd = 2)\nBooking.pending    # =\u003e #\u003cActiveRecord::Relation:0x0.....\u003e (WHERE status_cd = 3)\n```\n\n### Wait, there's more!\n\n- Too tired of always adding the integer values? Try:\n\n  ```ruby\n  class User \u003c ActiveRecord::Base\n    as_enum :status, %i{deleted active disabled}\n    # translates to: { deleted: 0, active: 1, disabled: 2 }\n  end\n  ```\n\n  **Disclaimer**: if you _ever_ decide to reorder this array, beware that any\n  previous mapping is lost. So it's recommended to create mappings (that might\n  change) using hashes instead of arrays. For stuff like gender it might be\n  probably perfectly fine to use arrays though.\n- You can store as string values instead of integer values if your database column\n  has the type `string` or `text`:\n\n  ```ruby\n  class User \u003c ActiveRecord::Base\n    as_enum :status, [:deleted, :active, :disabled], map: :string\n  end\n\n  User.create!(status: :active) #=\u003e #\u003cUser id: 1, status_cd: \"active\"\u003e\n  ```\n- Want to use `SimpleEnum` in an ActiveModel, or other class, just add:\n\n  ```ruby\n  class MyModel\n    extend SimpleEnum::Attribute\n    attr_accessor :gender_cd\n    as_enum :gender, [:male, :female]\n  end\n  ```\n- Maybe you've columns named differently than the proposed `{column}_cd` naming scheme, feel free to use any column name\n  by providing an option:\n\n  ```ruby\n  class User \u003c ActiveRecord::Base\n    as_enum :gender, [:male, :female], source: :sex\n  end\n  ```\n\n  Starting with 2.0 it's possible to use the same source name as column name.\n- By default ActiveRecord dirty methods are generated:\n\n  ```ruby\n  user = User.male.first\n  user.gender = :female\n  user.gender_was\n  # =\u003e :male\n  ```\n- Need to provide custom options for the mongoid field, or skip the automatically generated field?\n\n  ```ruby\n  # skip field generation\n  field :gender_cd # \u003c- create field manually (!)\n  as_enum :gender, [:male, :female], field: false\n\n  # custom field options (directly passed to Mongoid::Document#field)\n  as_enum :gender, [:male, :female], field: { :type =\u003e Integer, :default =\u003e 1 }\n  ```\n- To validate enum values simply make use of a `validates :gender, presence: true` validation.\n  If an invalid value is assigned, the gender is set to `nil` by default.\n- If the shortcut methods (like `female?`, `female!` or `User.male`) conflict with something in your class, it's possible to\n  define a prefix:\n  ```ruby\n  class User \u003c ActiveRecord::Base\n    as_enum :gender, %w{male female}, prefix: true\n  end\n\n  jane = User.new gender: :female\n  jane.gender_female? # =\u003e true\n  User.gender_females  # =\u003e \u003cActiveRecord::Relation...WHERE gender_cd = 1.\u003e\n  ```\n  The `:prefix` option not only takes a boolean value as an argument, but instead can also be supplied a custom\n  prefix, so with `prefix: 'foo'` all shortcut methods would look like: `foo_\u003csymbol\u003e`\n- To define which methods are generated it's possible to set `with:` option, by\n  default `with:` is set to `[:attribute, :dirty, :scope]`.\n\n  1. `:attribute` - generates the `male?` and `male!` accessor methods\n  2. `:dirty` - adds the `gender_was` and `gender_changed?` dirty methods\n  3. `:scope` - adds the class level scopes, **if** the `scope` method is present\n\n- By default the value is set to `nil` when the user sets an invalid value,\n  this behavior can be changed by setting the `accessor:` option. At the moment\n  there are three different behaviors:\n\n  1. `:default` - which sets the value simply to `nil`\n  2. `:whiny` - raises an ArgumentError when trying to set an invalid value\n  3. `:ignore` - keeps the existing value\n\n  ```ruby\n  class User \u003c ActiveRecord::Base\n    as_enum :gender, %w{male female}, accessor: :whiny\n  end\n  User.new(gender: \"dunno\") # =\u003e raises ArgumentError\n  ```\n\n  See `lib/simple_enum/accessors/*` for more.\n\n- To define any option globally, e.g. never generating dirty methods, create\n  an initializer and add:\n\n  ```ruby\n  # See lib/simple_enum.rb for other options\n  SimpleEnum.with = [:attribute, :scope]\n  ```\n\n### View Helpers\n\nRequire translated enum values? See [SimpleEnum::ViewHelpers][VE.rb] for more\ndetails and functions. _Disclaimer_: these methods are release candidate quality\nso expect them to change in future versions of SimpleEnum.\n\n- Translate the current value in a view:\n\n  ```ruby\n  translate_enum user, :gender # =\u003e \"Frau\" # assuming :de and translations exist\n  te user, :gender # translate_enum is also aliased to te\n  ```\n\n  Provide translations in the i18n yaml file like:\n\n  ```ruby\n    de:\n      enums:\n        gender:\n          female: 'Frau'\n          male: 'Mann'\n  ```\n\n- Build a select tag with a translated dropdown and symbol as value:\n\n  ```ruby\n  select :user, :gender, enum_option_pairs(User, :gender)\n  ```\n\n- ...and one with the index as value:\n\n  ```ruby\n  select :user, :gender_cd, enum_option_pairs(User, :gender, true)\n  ```\n\n## Extensions\n\n`simple_enum` provides hooks to extend its functionality, starting with 2.3.0\nthe following extensions can be used:\n\n- **Multi-select enum** support for SimpleEnum:\n  [simple_enum-multiple](https://github.com/bbtfr/simple_enum-multiple)\n- **Persistence values**, i.e. store values in the DB:\n  [simple_enum-persistence](https://github.com/bbtfr/simple_enum-persistence)\n- **Scopes**, scopes helper for ActiveRecord enum attributes:\n  [simple_enum-scopes](https://github.com/aovertus/simple_enum-scopes)\n\n## Best practices\n\nDo not use values named after existing, or well known method names, like `new`, `create` etc.\n\n```ruby\n# BAD, conflicts with Rails ActiveRecord Methods (!)\nas_enum :handle, [:new, :create, :update]\n\n# GOOD, prefixes all methods\nas_enum :handle, [:new, :create, :update], prefix: true\n```\n\nSearching for certain values by using the finder methods:\n\n```ruby\nUser.females # =\u003e returns an ActiveRecord::Relation\n```\n\nContributors\n------------\n\n- [@dmitry](https://github.com/dmitry) - bugfixes and other improvements\n- [@tarsolya](https://github.com/tarsolya) - implemented all the ruby 1.9 and rails 3 goodness!\n- [@dbalatero](https://github.com/dbalatero) - rails 2.3.5 bugfix \u0026 validator fixes\n- [@johnthethird](https://github.com/johnthethird) - feature for `_for_select` to return the values\n- @sinsiliux - ruby 1.9 fixes and removed AR dependency\n- [@sled](https://github.com/sled) - mongoid support\n- [@abrom](https://github.com/abrom) - `find_by_...` method\n- [@mhuggins](https://github.com/mhuggins) - translations fixes\n- [@patbenatar](https://github.com/patbenatar) - for helping move towards 2.0 (scopes et all)\n- [@abacha](https://github.com/abacha) - translation helpers, README fixes\n- [@bbtfr](https://github.com/bbtfr) - for support, ideas and pushing extensions\n- and all others: https://github.com/lwe/simple_enum/graphs/contributors thanks\n\nLicense \u0026 Copyright\n-------------------\n\nCopyright (c) 2011-2015 by Lukas Westermann, Licensed under MIT License (see LICENSE file)\n\n[VE.rb]: https://github.com/lwe/simple_enum/blob/master/lib/simple_enum/view_helpers.rb\n","funding_links":[],"categories":["Active Record Plugins","Ruby"],"sub_categories":["Active Record Enumerations"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flwe%2Fsimple_enum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flwe%2Fsimple_enum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flwe%2Fsimple_enum/lists"}