Class: HaveAPI::Validators::Presence

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

Overview

Checks the value is present and not empty.

Short form:

string :param, required: true

Full form:

string :param, required: {
  empty: true/false,
  message: 'the error message'
}

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



28
29
30
31
32
33
# File 'lib/haveapi/validators/presence.rb', line 28

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

#setupObject



18
19
20
21
22
23
24
25
26
# File 'lib/haveapi/validators/presence.rb', line 18

def setup
  return useless if simple? && !take

  @empty = take(:empty, false)
  @message = take(
    :message,
    @empty ? 'must be present' : 'must be present and non-empty'
  )
end

#valid?(v) ⇒ Boolean

Returns:



35
36
37
38
39
40
41
# File 'lib/haveapi/validators/presence.rb', line 35

def valid?(v)
  return false if v.nil?
  return !v.strip.empty? if !@empty && v.is_a?(::String)

  # FIXME: other data types?
  true
end