File: uuid.rb

package info (click to toggle)
ruby-valid 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 132 kB
  • sloc: ruby: 311; makefile: 2
file content (47 lines) | stat: -rw-r--r-- 1,048 bytes parent folder | download
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
41
42
43
44
45
46
47
module Validation
  # UUID rule
  module Rule
    class Uuid
      class UnknownVersion < StandardError; end
      # params can be any of the folowing:
      #
      # - :version - v4
      #              v5
      #              uuid (Any valid uuid)
      #
      # Example:
      #
      # {:version => v4}
      def initialize(params)
        @params = params
      end

      def params
        @params
      end

      def valid_value?(value)
        value.nil? || !!uuid_regex.match(value.to_s)
      rescue UnknownVersion
        false
      end

      def error_key
        :uuid
      end

      private

      VERSION_REGEX = {
        'uuid' => /^[0-9A-F]{8}-[0-9A-F]{4}-[1-5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
        'v4'   => /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
        'v5'   => /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
      }

      def uuid_regex
        VERSION_REGEX.fetch(params[:version]) { raise UnknownVersion }
      end

    end
  end
end