Class: Errapi::Validations::Length
- Defined in:
- lib/errapi/validations/length.rb
Constant Summary collapse
- CHECKS =
{ is: :==, minimum: :>=, maximum: :<= }.freeze
- REASONS =
{ is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Length
constructor
A new instance of Length.
- #validate(value, context, options = {}) ⇒ Object
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 = {}) ⇒ Length
Returns a new instance of Length.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/errapi/validations/length.rb', line 6 def initialize = {} constraints = .select{ |k,v| OPTIONS.include? k } if constraints.empty? raise ArgumentError, "The :is, :minimum/:maximum or :within options must be supplied (but only :minimum and :maximum can be used together)." elsif .key?(:is) && constraints.length != 1 raise ArgumentError, "The :is option cannot be combined with :minimum, :maximum or :within." elsif .key?(:is) check_numeric! [:is] elsif .key?(:within) if .key?(:minimum) || .key?(:maximum) raise ArgumentError, "The :within option cannot be combined with :minimum or :maximum." else check_range! [:within] end else check_numeric! [:minimum] if .key? :minimum check_numeric! [:maximum] if .key? :maximum end @constraints = actual_constraints constraints end |
Instance Method Details
#validate(value, context, options = {}) ⇒ Object
29 30 31 32 33 34 35 36 37 38 |
# File 'lib/errapi/validations/length.rb', line 29 def validate value, context, = {} return unless value.respond_to? :length actual_length = value.length CHECKS.each_pair do |key,check| next unless check_value = @constraints[key] next if actual_length.send check, check_value context.add_error reason: REASONS[key], check_value: check_value, checked_value: actual_length, constraints: @constraints end end |