Class: SimpleValidate::ValidatesTypeOf

Inherits:
ValidatesBase show all
Defined in:
lib/simple_validate/validates_type_of.rb

Constant Summary collapse

SUPPORTED_TYPES =
i[string integer float boolean].freeze

Instance Attribute Summary

Attributes inherited from ValidatesBase

#attribute, #condition, #message

Instance Method Summary collapse

Constructor Details

#initialize(attribute, options) ⇒ ValidatesTypeOf

Returns a new instance of ValidatesTypeOf.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
# File 'lib/simple_validate/validates_type_of.rb', line 7

def initialize(attribute, options)
  @allow_nil = options[:allow_nil]
  @type = options[:as]

  raise ArgumentError unless @type && SUPPORTED_TYPES.include?(@type)

  super(attribute, options[:message] ||
    "must be #{Utils.article(@type)} #{@type}", options[:if] || proc { true })
end

Instance Method Details

#valid?(instance) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/simple_validate/validates_type_of.rb', line 17

def valid?(instance)
  val = instance.send(attribute)

  return true if val.nil? && @allow_nil == true

  if @type == :boolean
    [true, false].include? val
  else
    klass = Utils.classify(@type)
    val.is_a?(klass)
  end
end