Have a legacy database and need some enumerations in your models to match those stupid '4 rows/2 columns' tables with foreign keys and stop doing joins just to fetch a simple description? Or maybe use some integers instead of strings as the code for each value of your enumerations?
I18n and ActiveRecord/Mongoid/MongoMapper rspec, helpers, activeadmin
- Default Value
- Formtastic support
- Select Form Helpers
- l18n
- Formtastic support
- Generators
- Modify member of enum
- I18n
- As a collection
- Default Value
- Back Reference to Owning Object
- Validation
- Select Form Helpers
- Documented Easy Code
- Most important feature is support for string and integer values in db
- I18n
- Easy Code in 2 files mostly
- Helpers
- No Default values
class RelationshipStatus < EnumerateIt::Base
associate_values(
:single => [1, 'Single'],
:married => [2, 'Married'],
:widow => [3, 'Widow'],
:divorced => [4, 'Divorced']
)
end
- When calling methods like
to_a
andto_json
, the returned values will be sorted using the translation for each one of the enumeration values. If you want to overwrite the default sort mode, you can use thesort_mode
class method.
class RelationshipStatus < EnumerateIt::Base
associate_values :married => 1, :single => 2
sort_by :value
end
- Not Only AR
class Person
extend EnumerateIt
attr_accessor :relationship_status
has_enumeration_for :relationship_status, :with => RelationshipStatus
end
- Have Generators
meh,, not simple for ActiveModel (including validations and i18n helpers Mongoid
-
ActiveRecord integration
-
ActionView form helpers
-
Custom labels
-
Formtastic
-
Scaffold generator integration
-
Definable enumeration labels
-
Enum helper methods
-
Dynamic predicate methods
-
Initialization
-
OLD State pattern support (enumerated_state) https://github.com/jeffp/enumerated_state
-
old
-
many files, many files for integration
-
no integration mongoid
-
No rails i18n
-
Too many issues
- Form Helpers
- Storage Backends + l18n
- ordering
- validations
Two ways. Symbols (:foo notation) or constants (FOO notation).
Symbols are appropriate when you want to enhance readability without littering code with literal strings.
postal_code[:minnesota] = "MN"
postal_code[:new_york] = "NY"
Constants are appropriate when you have an underlying value that is important. Just declare a module to hold your constants and then declare the constants within that.
module Foo
BAR = 1
BAZ = 2
BIZ = 4
end
flags = Foo::BAR | Foo::BAZ # flags = 3
http://stackoverflow.com/questions/265725/what-is-the-best-way-to-handle-constants-in-ruby-when-using-rails
http://schneide.wordpress.com/2010/12/13/avoid-switch-use-enum/ http://programmers.stackexchange.com/questions/191063/should-classes-enums-and-other-entities-be-placed-in-separate-files http://simpleprogrammer.com/2012/02/21/refactoring-switches-to-classes/