Module: Sequel::Plugins::EnumGuard

Defined in:
lib/sequel/plugins/enum_guard.rb

Overview

EnumGuard adds runtime checking for Sequel's pg_enum types.

When enabled, the plugin automatically searches model's schema for enum fields and adds custom setter to prevent invalid value to be set on enum field. The plugin also adds enums class method to the model exposing Hash of known enum fields with their value.

The plugin was loosely inspired by sequel_enum plugin.

Example:

Sequel::Model.plugin :enum_guard # The plugin is intended to be enabled globally

class MyModel < Sequel::Model
end

MyModel.enum_fields#=> {column1: ['a', 'b'], column2: ['c', 'd', nil]}


instance = MyModel.new
instance.column1 = 'a'  # Values can be set both as symbols or strings
instance.column2 = :c

instance.column2        # Field's value is returned as string
#=> 'c'

instance.column2 = nil  # NULL fields can be set to nil, as seen in .enum_fields


instance.column1 = 'invalid value'#=> ArgumentError

instance.column1 = nil#=> ArgumentError

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.configure(model) ⇒ void

This method returns an undefined value.


44
45
46
47
48
# File 'lib/sequel/plugins/enum_guard.rb', line 44

def self.configure(model)
  model.instance_eval do
    send(:create_enum_setters) if @dataset
  end
end