Class: PureValidator::Validators::LengthValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/pure_validator/validators/length_validator.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, options) ⇒ LengthValidator

Returns a new instance of LengthValidator.



17
18
19
20
# File 'lib/pure_validator/validators/length_validator.rb', line 17

def initialize(object, options)
  @object, @options = object, options
  @errors = []
end

Instance Attribute Details

#errorsObject

Returns the value of attribute errors.



16
17
18
# File 'lib/pure_validator/validators/length_validator.rb', line 16

def errors
  @errors
end

#objectObject

Returns the value of attribute object.



16
17
18
# File 'lib/pure_validator/validators/length_validator.rb', line 16

def object
  @object
end

#optionsObject

Returns the value of attribute options.



16
17
18
# File 'lib/pure_validator/validators/length_validator.rb', line 16

def options
  @options
end

Class Method Details

.validate(object, options) ⇒ Array

Validates that given object has correct length

Parameters:

  • object (#length)

    object to validate

  • options (Hash)

    validation options, e.g. { min: 2, max: 4, equal_to: 3, not_equal_to: 6 }

Returns:

  • (Array)

    empty array if object is valid, array of error messages otherwise



7
8
9
# File 'lib/pure_validator/validators/length_validator.rb', line 7

def self.validate(object, options)
  self.new(object, options).validate
end

.validate_options(options) ⇒ Object



11
12
13
14
# File 'lib/pure_validator/validators/length_validator.rb', line 11

def self.validate_options(options)
  PureValidator::ArgsValidator.is_hash!(options, :validation_rule)
  PureValidator::ArgsValidator.has_only_allowed_keys!(options, [:min, :max, :equal_to, :not_equal_to], :validation_rule)
end

Instance Method Details

#add_error!(key, length) ⇒ Object



40
41
42
# File 'lib/pure_validator/validators/length_validator.rb', line 40

def add_error!(key, length)
  errors << PureValidator::I18n.t(key, length: length)
end

#handle(key, condition, error_key) ⇒ Object



33
34
35
36
37
38
# File 'lib/pure_validator/validators/length_validator.rb', line 33

def handle(key, condition, error_key)
  return unless options[key]
  if object.length.send(condition, options[key])
    add_error!(error_key, options[key])
  end
end

#validateObject



22
23
24
25
26
27
28
29
30
31
# File 'lib/pure_validator/validators/length_validator.rb', line 22

def validate
  return errors if object.nil?

  handle(:min, :<, 'errors.can_not_be_less_than')
  handle(:max, :>, 'errors.can_not_be_more_than')
  handle(:equal_to, :!=, 'errors.should_be_equal_to')
  handle(:not_equal_to, :==, 'errors.should_not_be_equal_to')

  errors
end