Class: Knight::Rule

Inherits:
Object
  • Object
show all
Includes:
AbstractType
Defined in:
lib/knight/rule.rb,
lib/knight/rule/format.rb,
lib/knight/rule/presence.rb,
lib/knight/rule/inclusion.rb,
lib/knight/rule/exact_length.rb,
lib/knight/rule/range_length.rb,
lib/knight/rule/maximum_length.rb,
lib/knight/rule/minimum_length.rb

Overview

An abstract class of a rule

Defined Under Namespace

Classes: ExactLength, Format, Inclusion, MaximumLength, MinimumLength, Presence, RangeLength

Constant Summary collapse

DEFAULT_MESSAGE =
''.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

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.

Initialize a rule

Parameters:

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

    for this rule

Options Hash (options):

  • :message (String)

    error message



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

def initialize(attribute_name, options = {})
  @attribute_name = attribute_name
  @options        = options
  @message        = @options.fetch(:message, self.class::DEFAULT_MESSAGE)
end

Instance Attribute Details

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

Attribute name to validate

Returns:

  • (Symbol)


17
18
19
# File 'lib/knight/rule.rb', line 17

def attribute_name
  @attribute_name
end

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

Message to displayed when rule is violated

Returns:

  • (String)


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

def message
  @message
end

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

Attribute name to validate

Returns:

  • (Symbol)


24
25
26
# File 'lib/knight/rule.rb', line 24

def options
  @options
end

Instance Method Details

#error(resource) ⇒ Error?

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.

Return error if the rule not satisfied

Parameters:

  • resource (Object)

Returns:

  • (Error)

    if the rule not matched

  • (nil)

    if the rule is satisfied



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

def error(resource)
  value = resource.public_send(attribute_name)
  Error.new(self, resource) unless matches?(value)
end

#to_hashHash

Return the rule as a hash

Examples:

hash = rule.to_hash

Returns:

  • (Hash)


70
71
72
# File 'lib/knight/rule.rb', line 70

def to_hash
  { attribute: attribute_name }.freeze
end