Module | Sequel::Plugins::AutoValidations |
In: |
lib/sequel/plugins/auto_validations.rb
|
The auto_validations plugin automatically sets up three types of validations for your model columns:
To determine the columns to use for the not_null validations and the types for the type validations, the plugin looks at the database schema for the model‘s table. To determine the unique validations, Sequel looks at the indexes on the table. In order for this plugin to be fully functional, the underlying database adapter needs to support both schema and index parsing.
This plugin uses the validation_helpers plugin underneath to implement the validations. It does not allow for any per-column validation message customization, but you can alter the messages for the given type of validation on a per-model basis (see the validation_helpers documentation).
You can skip certain types of validations from being automatically added via:
Model.skip_auto_validations(:not_null)
If you want to skip all auto validations (only useful if loading the plugin in a superclass):
Model.skip_auto_validations(:all)
By default, the plugin uses a not_null validation for NOT NULL columns, but that can be changed to a presence validation using an option:
Model.plugin :auto_validations, :not_null=>:presence
This is useful if you want to enforce that NOT NULL string columns do not allow empty values.
Usage:
# Make all model subclass use auto validations (called before loading subclasses) Sequel::Model.plugin :auto_validations # Make the Album class use auto validations Album.plugin :auto_validations
# File lib/sequel/plugins/auto_validations.rb, line 46 46: def self.apply(model, opts=OPTS) 47: model.instance_eval do 48: plugin :validation_helpers 49: @auto_validate_presence = false 50: @auto_validate_not_null_columns = [] 51: @auto_validate_explicit_not_null_columns = [] 52: @auto_validate_unique_columns = [] 53: @auto_validate_types = true 54: end 55: end
Setup auto validations for the model if it has a dataset.
# File lib/sequel/plugins/auto_validations.rb, line 58 58: def self.configure(model, opts=OPTS) 59: model.instance_eval do 60: setup_auto_validations if @dataset 61: if opts[:not_null] == :presence 62: @auto_validate_presence = true 63: end 64: end 65: end