Module: Sequel::Plugins::PgAutoValidateEnums

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

Overview

The pg_auto_validate_enums plugin implements automatic validations for enum columns, ensuring that enum columns have a valid value. With this plugin, trying to save with an invalid enum value results in Sequel::ValidationFailed before saving, instead of Sequel::DatabaseError (wrapping PG::InvalidTextRepresentation or similar exception) during saving.

class Person < Sequel::Model
  # assume state enum column with allowed values active and inactive
  plugin :pg_auto_validate_enums
end
p = Person.new(state: "active").valid? # => true
p = Person.new(state: "inactive").valid? # => true
p = Person.new(state: "other").valid? # => false

While you can load this into individual model classes, typical use would be to load it into Sequel::Model or the appropriate model base class, and have all models that inherit from that class automatically pick it up.

This plugin depends on the validation_helpers plugin.

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.apply(model, opts = OPTS) ⇒ Object

Load the validation_helpers plugin.



26
27
28
# File 'lib/sequel/plugins/pg_auto_validate_enums.rb', line 26

def self.apply(model, opts=OPTS)
  model.plugin(:validation_helpers)
end

.configure(model, opts = OPTS) ⇒ Object

Load the pg_enum extension into the database, and reload the schema if it is already loaded. The opts given are used for the validates_includes validations (with allow_nil: true and from: :values enabled by default, to avoid issues with nullable enum columns and cases where the column method has been overridden.



35
36
37
38
39
40
41
42
43
44
# File 'lib/sequel/plugins/pg_auto_validate_enums.rb', line 35

def self.configure(model, opts=OPTS)
  model.instance_exec do
    db.extension(:pg_enum) unless @db.instance_variable_get(:@enum_labels)
    if @db_schema
      get_db_schema(true)
      
    end
    @pg_auto_validate_enums_opts = {allow_nil: true, from: :values}.merge!(opts).freeze
  end
end