Class: Spree::Validations::DbMaximumLengthValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
app/models/spree/validations/db_maximum_length_validator.rb

Overview

Validates a field based on the maximum length of the underlying DB field, if there is one.

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ DbMaximumLengthValidator

Returns a new instance of DbMaximumLengthValidator

Raises:

  • (ArgumentError)

6
7
8
9
10
# File 'app/models/spree/validations/db_maximum_length_validator.rb', line 6

def initialize(options)
  super
  @field = options[:field].to_s
  raise ArgumentError, 'a field must be specified to the validator' if @field.blank?
end

Instance Method Details

#validate(record) ⇒ Object


12
13
14
15
16
17
18
19
# File 'app/models/spree/validations/db_maximum_length_validator.rb', line 12

def validate(record)
  warn '`Spree::Validations::DbMaximumLengthValidator` is deprecated. Use `DbMaximumLengthValidator` instead.'
  limit = record.class.columns_hash[@field].limit
  value = record[@field.to_sym]
  if value && limit && value.to_s.length > limit
    record.errors.add(@field.to_sym, :too_long, count: limit)
  end
end