Class: Knight::Rule::Inclusion

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

Overview

A rule for checking the inclusion of a value

Constant Summary collapse

DEFAULT_MESSAGE =
'%{attribute} is not included in the list'.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, within, options = {}) ⇒ undefined

Initialize an inclusion rule

Examples:

rule = Knight::Rule::Inclusion.new(:username, ['john', 'jane'])

Parameters:

  • attribute_name (Symbol)
  • within (Range, Array)
  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :message (String)

    error_message



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

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

Instance Attribute Details

#withinRange, Array (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.

Inclusion value

Returns:

  • (Range, Array)


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

def within
  @within
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 (Object)

Returns:

  • (true)

    if the value within inclusion value

  • (false)

    otherwise



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

def matches?(value)
  within.respond_to?(:cover?) ? within.cover?(value) : within.include?(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/inclusion.rb', line 55

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