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

- (DbMaximumLengthValidator) initialize(options)

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.new("a field must be specified to the validator") if @field.blank?
end

Instance Method Details

- (Object) validate(record)



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

def validate(record)
  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