The enum plugin allows for easily adding methods to modify the value of a column. It allows treating the column itself as an enum, returning a symbol for the related enum value. It also allows for setting up dataset methods to easily find records having or not having each enum value.
After loading the plugin, you can call the enum
method to define the methods. The enum
method accepts a symbol for the underlying database column, and a hash with symbol keys for the enum values. For example, the following call:
Album.enum :status_id, good: 1, bad: 2
Will define the following instance methods:
Album#good! |
Change |
Album#bad! |
Change |
Album#good? |
Return whether |
Album#bad? |
Return whether |
It will override the following instance methods:
Album#status_id |
Return |
Album#status_id= |
Allow calling with |
If will define the following dataset methods:
Album.dataset.good |
Return a dataset filtered to rows where |
Album.dataset.not_good |
Return a dataset filtered to rows where |
Album.dataset.bad |
Return a dataset filtered to rows where |
Album.dataset.not_bad |
Return a dataset filtered to rows where |
When calling enum
, you can also provide the following options:
:prefix |
Use a prefix for methods defined for each enum value. If |
:suffix |
Use a suffix for methods defined for each enum value. If |
:override_accessors |
Set to |
:dataset_methods |
Set to |
Note that this does not use a true enum column in the database. If you are looking for enum support in the database, and your are using PostgreSQL, Sequel
supports that via the pg_enum Database
extension.
Usage:
# Make all model subclasses handle enums Sequel::Model.plugin :enum # Make the Album class handle enums Album.plugin :enum