Module: Sequel::Plugins::Enum
- Defined in:
- lib/sequel/plugins/enum.rb
Overview
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
status_id
to1
(does not save the receiver) - Album#bad!
-
Change
status_id
to2
(does not save the receiver) - Album#good?
-
Return whether
status_id
is1
- Album#bad?
-
Return whether
status_id
is2
It will override the following instance methods:
- Album#status_id
-
Return
:good
/:bad
instead of1
/2
(other values returned as-is) - Album#status_id=
-
Allow calling with
:good
/:bad
to setstatus_id
to1
/2
(other values, such as'good'
/'bad'
set as-is)
If will define the following dataset methods:
- Album.dataset.good
-
Return a dataset filtered to rows where
status_id
is1
- Album.dataset.not_good
-
Return a dataset filtered to rows where
status_id
is not1
- Album.dataset.bad
-
Return a dataset filtered to rows where
status_id
is2
- Album.dataset.not_bad
-
Return a dataset filtered to rows where
status_id
is not2
When calling enum
, you can also provide the following options:
- :prefix
-
Use a prefix for methods defined for each enum value. If
true
is provided at the value, use the column name as the prefix. For example, withprefix: 'status'
, the instance methods defined above would bestatus_good?
,status_bad?
,status_good!
, andstatus_bad!
, and the dataset methods defined would bestatus_good
,status_not_good
,status_bad
, andstatus_not_bad
. - :suffix
-
Use a suffix for methods defined for each enum value. If
true
is provided at the value, use the column name as the suffix. For example, withsuffix: 'status'
, the instance methods defined above would begood_status?
,bad_status?
,good_status!
, andbad_status!
, and the dataset methods defined would begood_status
,not_good_status
,bad_status
, andnot_bad_status
. - :override_accessors
-
Set to
false
to not override the column accessor methods. - :dataset_methods
-
Set to
false
to not define dataset methods.
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
Defined Under Namespace
Modules: ClassMethods