Sylver
Sylver

Reputation: 2453

Sequel : DRY between schema migration and model validate method

I'm wondering if I miss a way to avoid repeat validation code in my Sequel::Model#validate subclass method since I've already put all constraints into my migration file.

Here's a simple example of what I'm talking about :

  Sequel.migration do
    change do
      create_table :users do
        primary_key :id
        String  :name, :null => false, :unique => true
      end
    end
  end

  class User < Sequel::Model
    def validate
      super
      validates_presence :name
      validates_unique :name
      validates_type String :name
    end
  end

It seems very painful and errors prone to have to repeat all the constraints in the validate method. Did I miss something or there's no other way to do that ?

Any advice will be appreciated, thanks

Upvotes: 0

Views: 842

Answers (2)

tmaier
tmaier

Reputation: 985

Sequel has some nice plugins and extensions.

Sequel::Model.plugin(:auto_validations)
Sequel::Model.plugin(:constraint_validations)

and

DB.extension(:constraint_validations)

auto_validations

The auto_validations plugin automatically sets up three types of validations for your model columns:

  • type validations for all columns
  • not_null validations on NOT NULL columns (optionally, presence validations)
  • unique validations on columns or sets of columns with unique indexes

See http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/AutoValidations.html

constraint_validations

The constraint_validations extension is designed to easily create database constraints inside create_table and alter_table blocks. It also adds relevant metadata about the constraints to a separate table, which the constraint_validations model plugin uses to setup automatic validations.

See http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/constraint_validations_rb.html and http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/ConstraintValidations.html

Your example would look like this

Sequel::Model.plugin(:auto_validations)
Sequel::Model.plugin(:constraint_validations)

Sequel.migration do
  up do
    extension(:constraint_validations)

    create_table :users do
      primary_key :id
      String :name, :null => false, :unique => true

      validate do
        presence :name,
                 name: :presence_name
      end
    end
  end

  down do
    extension(:constraint_validations)

    drop_table(:users)
  end
end

class User < Sequel::Model
end

Upvotes: 1

Ant0ha
Ant0ha

Reputation: 557

I think, it's normal. Don't worry.

Upvotes: 0

Related Questions