File: length.rb

package info (click to toggle)
ruby-valid 1.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 128 kB
  • sloc: ruby: 309; makefile: 2
file content (40 lines) | stat: -rw-r--r-- 1,006 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
module Validation
  module Rule
    # Length rule
    class Length
      # params can be any of the following:
      #
      #  - :minimum - at least this many chars
      #  - :maximum - at most this many chars
      #  - :exact - exactly this many chars
      #
      #  Example:
      #
      #  {:minimum => 3, :maximum => 10}
      #  {:exact => 10}
      def initialize(params)
        @params = params
      end

      # returns the params given in the constructor
      def params
        @params
      end

      # determines if value is valid according to the constructor params
      def valid_value?(value)
        @params.each_pair do |key, param|
          return false if key == :minimum && (value.nil? || value.length < param)
          return false if key == :maximum && !value.nil? && value.length > param
          return false if key == :exact && (value.nil? || value.length != param)
        end

        true
      end

      def error_key
        :length
      end
    end
  end
end