Class: Knight::Rule::Format

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

Overview

A rule for checking the format of a value

Constant Summary collapse

DEFAULT_MESSAGE =
'%{attribute} has an invalid format'.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, regexp, options = {}) ⇒ undefined

Initialize a format rule

Examples:

rule = Knight::Rule::Format.new(:username, /A-Z0-9/)

Parameters:

  • attribute_name (Symbol)
  • regexp (Regexp)
  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :message (String)

    error_message



30
31
32
33
# File 'lib/knight/rule/format.rb', line 30

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

Instance Attribute Details

#regexpRegexp (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.

Regexp format

Returns:

  • (Regexp)


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

def regexp
  @regexp
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 value presence

Parameters:

  • value (String)

Returns:

  • (true)

    if matched with the format

  • (false)

    otherwise



43
44
45
# File 'lib/knight/rule/format.rb', line 43

def matches?(value)
  !!(regexp =~ value)
end

#to_hashHash

Return the rule as a hash

Examples:

hash = rule.to_hash

Returns:

  • (Hash)


55
56
57
58
59
# File 'lib/knight/rule/format.rb', line 55

def to_hash
  super.merge({
    format: regexp
  }).freeze
end