Class: Predicates::Length

Inherits:
Base
  • Object
show all
Defined in:
lib/predicates/length.rb

Overview

Lets you declare a min/max/exact length for something. This works for arrays and strings both.

Options

  • :above [integer] - when the attribute has a minimum

  • :below [integer] - when the attribute has a maximum

  • :range [range] - when the attribute has a minimum and a maximum

  • :exactly [integer] - when the attribute must be exactly some length

Examples

field_has_length :exactly => 3
field_has_length :above => 5
field_has_length :range => 4..8

Direct Known Subclasses

Size

Instance Attribute Summary collapse

Attributes inherited from Base

#full_message, #or_empty, #validate_if, #validate_on

Instance Method Summary collapse

Methods inherited from Base

#allow_empty?, #error, #initialize, #to_human

Constructor Details

This class inherits a constructor from Predicates::Base

Instance Attribute Details

#aboveObject

when the length has just a min



15
16
17
# File 'lib/predicates/length.rb', line 15

def above
  @above
end

#belowObject

when the length has just a max



18
19
20
# File 'lib/predicates/length.rb', line 18

def below
  @below
end

#exactlyObject

when the length must be exact



24
25
26
# File 'lib/predicates/length.rb', line 24

def exactly
  @exactly
end

#rangeObject

when the length has both a max and a min



21
22
23
# File 'lib/predicates/length.rb', line 21

def range
  @range
end

Instance Method Details

#error_bindsObject



30
31
32
33
34
# File 'lib/predicates/length.rb', line 30

def error_binds
  self.range ?
    {:min => self.range.first, :max => self.range.last} :
    {:min => self.above, :max => self.below, :count => self.exactly}
end

#error_messageObject



26
27
28
# File 'lib/predicates/length.rb', line 26

def error_message
  @error_message || range_description
end

#normalize(v) ⇒ Object



51
52
53
# File 'lib/predicates/length.rb', line 51

def normalize(v)
  (v and v.is_a? String) ? v.gsub("\r\n", "\n") : v
end

#validate(value, record) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/predicates/length.rb', line 36

def validate(value, record)
  l = tokenize(value).length
  if self.exactly
    l == self.exactly
  elsif self.range
    self.range.include? l
  elsif self.above
    l > self.above
  elsif self.below
    l < self.below
  else
    true
  end
end