Class: HaveAPI::Validators::Inclusion

Inherits:
HaveAPI::Validator show all
Defined in:
lib/haveapi/validators/inclusion.rb

Overview

Checks that the value is from given set of allowed values.

Short form:

string :param, choices: %i(one two three)

Full form:

string :param, choices: {
  values: %i(one two three),
  message: 'the error message'
}

Option ‘choices` is an alias to `include`.

Instance Attribute Summary

Attributes inherited from HaveAPI::Validator

#message, #params

Instance Method Summary collapse

Methods inherited from HaveAPI::Validator

#initialize, name, #reconfigure, takes, use, use?, #useful?, #validate

Constructor Details

This class inherits a constructor from HaveAPI::Validator

Instance Method Details

#describeObject



37
38
39
40
41
42
# File 'lib/haveapi/validators/inclusion.rb', line 37

def describe
  {
    values: @values,
    message: @message
  }
end

#setupObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/haveapi/validators/inclusion.rb', line 20

def setup
  values = simple? ? take : take(:values)

  if values.is_a?(::Hash)
    @values = {}

    values.each do |k, v|
      @values[k.is_a?(::Symbol) ? k.to_s : k] = v
    end

  else
    @values = values.map { |v| v.is_a?(::Symbol) ? v.to_s : v }
  end

  @message = take(:message, '%{value} cannot be used')
end

#valid?(v) ⇒ Boolean

Returns:



44
45
46
47
48
49
50
51
# File 'lib/haveapi/validators/inclusion.rb', line 44

def valid?(v)
  if @values.is_a?(::Hash)
    @values.has_key?(v)

  else
    @values.include?(v)
  end
end