Class: Errapi::Validations::Format

Inherits:
Base
  • Object
show all
Defined in:
lib/errapi/validations/format.rb

Instance Method Summary collapse

Methods inherited from Base

#actual_option_value, #callable_option_type_error, #callable_option_value?, #callable_option_value_error, #exactly_one_option?

Constructor Details

#initialize(options = {}) ⇒ Format

Returns a new instance of Format.



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/errapi/validations/format.rb', line 4

def initialize options = {}
  unless key = exactly_one_option?(OPTIONS, options)
    raise ArgumentError, "Either :with or :without must be supplied (but not both)."
  end

  @format = options[key]
  @should_match = key == :with

  unless @format.kind_of?(Regexp) or callable_option_value?(@format)
    raise callable_option_type_error ":with (or :without)", "a regular expression", @format
  end
end

Instance Method Details

#validate(value, context, options = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/errapi/validations/format.rb', line 17

def validate value, context, options = {}

  regexp = actual_option_value @format, options
  unless regexp.kind_of? Regexp
    raise callable_option_value_error ":with (or :without)", "a regular expression", regexp
  end

  if !regexp.match(value.to_s) == @should_match
    context.add_error reason: :invalid_format, check_value: regexp
  end
end