Class: SimpleValidate::ValidatesLengthOf

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_validate/validates_length_of.rb

Defined Under Namespace

Classes: InvalidLengthOption

Constant Summary collapse

VALID_LENGTH_OPTIONS =
%i(maximum minimum in is)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attribute, options) ⇒ ValidatesLengthOf

Returns a new instance of ValidatesLengthOf.



8
9
10
11
12
13
14
# File 'lib/simple_validate/validates_length_of.rb', line 8

def initialize(attribute, options)
  @message          = options.delete(:message)
  @attribute        = attribute
  @options          = options
  check_options(@options)
  @length_validator = @options.select { |k, _| VALID_LENGTH_OPTIONS.include?(k) }
end

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



3
4
5
# File 'lib/simple_validate/validates_length_of.rb', line 3

def attribute
  @attribute
end

Instance Method Details

#check_options(options) ⇒ Object



33
34
35
36
37
# File 'lib/simple_validate/validates_length_of.rb', line 33

def check_options(options)
  if options.keys.size > 1 || !VALID_LENGTH_OPTIONS.include?(options.keys.first)
    raise InvalidLengthOption, "Invalid length option given #{@options.keys}"
  end
end

#messageObject



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/simple_validate/validates_length_of.rb', line 16

def message
  @message ||= begin
                 case @length_validator.keys.first
                 when :minimum
                   'is too short'
                 when :maximum
                   'is too long'
                 else
                   'is not the correct length'
                 end
               end
end

#valid?(instance) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
56
# File 'lib/simple_validate/validates_length_of.rb', line 53

def valid?(instance)
  actual_length = instance.send(attribute).length
  valid_length?(actual_length)
end

#valid_length?(actual_length) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/simple_validate/validates_length_of.rb', line 39

def valid_length?(actual_length)
  validator_key, valid_length = @length_validator.entries.first
  case validator_key
  when :minimum
    actual_length >= valid_length ? true : false
  when :maximum
    actual_length <= valid_length ? true : false
  when :in
    valid_length.member?(actual_length) ? true : false
  when :is
    actual_length == valid_length ? true : false
  end
end

#validatorObject



29
30
31
# File 'lib/simple_validate/validates_length_of.rb', line 29

def validator
  @options.entries.first
end