Class: TypeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/type_validator.rb,
lib/type_validator/error.rb,
lib/type_validator/version.rb,
lib/type_validator/default_validation.rb

Defined Under Namespace

Modules: Error

Constant Summary collapse

VERSION =
'1.0.0'
DEFAULT_VALIDATION_OPTIONS =
%w[instance_of is_a kind_of].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_validationObject



6
7
8
# File 'lib/type_validator/default_validation.rb', line 6

def self.default_validation
  @default_validation ||= :kind_of
end

.default_validation=(option) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/type_validator/default_validation.rb', line 10

def self.default_validation=(option)
  if DEFAULT_VALIDATION_OPTIONS.include?(String(option))
    @default_validation = option.to_sym
  else
    raise Error::InvalidDefaultValidation.new(option)
  end
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Raises:

  • (TypeError)


6
7
8
9
10
11
12
13
14
# File 'lib/type_validator.rb', line 6

def validate_each(record, attribute, value)
  return if options[:allow_nil] && value.nil?

  return unless error = validate_type_of(attribute, value)

  raise TypeError, "#{attribute} #{error}" if options[:strict]

  record.errors.add(attribute, error)
end