Class: Knight::Rule::RangeLength

Inherits:
Knight::Rule show all
Defined in:
lib/knight/rule/range_length.rb

Overview

A rule for checking the length of a value

Constant Summary collapse

DEFAULT_MESSAGE =
'%{attribute} has an invalid length'.freeze

Instance Attribute Summary collapse

Attributes inherited from Knight::Rule

#attribute_name, #message, #options

Instance Method Summary collapse

Methods inherited from Knight::Rule

#error

Constructor Details

#initialize(attribute_name, range, options = {}) ⇒ undefined

Initialize a length rule

Examples:

rule = Knight::Rule::RangeLength.new(:username, 3..20)

Parameters:

  • attribute_name (Symbol)
  • range (Range)
  • options (Hash) (defaults to: {})

    for this rule

Options Hash (options):

  • :message (String)

    error_message



31
32
33
34
# File 'lib/knight/rule/range_length.rb', line 31

def initialize(attribute_name, range, options = {})
  super(attribute_name, options)
  @range = range
end

Instance Attribute Details

#rangeRange (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Length value

Returns:

  • (Range)


15
16
17
# File 'lib/knight/rule/range_length.rb', line 15

def range
  @range
end

Instance Method Details

#matches?(value) ⇒ true, false

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Check length of the value

Parameters:

  • value (Object)

Returns:

  • (true)

    if the length is accepted

  • (false)

    otherwise



44
45
46
# File 'lib/knight/rule/range_length.rb', line 44

def matches?(value)
  range.cover?(value.length)
end

#to_hashHash

Return the rule as a hash

Examples:

hash = rule.to_hash

Returns:

  • (Hash)


56
57
58
59
60
61
# File 'lib/knight/rule/range_length.rb', line 56

def to_hash
  super.merge({
    minimum: range.min,
    maximum: range.max
  }).freeze
end