Class: Axn::Validators::TypeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/axn/core/validation/validators/type_validator.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.apply_syntactic_sugar(value, _fields) ⇒ Object



8
9
10
11
12
# File 'lib/axn/core/validation/validators/type_validator.rb', line 8

def self.apply_syntactic_sugar(value, _fields)
  return value if value.is_a?(Hash)

  { klass: value }
end

.value_matches?(value, klass:, allow_blank: false) ⇒ Boolean

Shared matcher used by OfValidator for per-element type checking.

Returns:

  • (Boolean)


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/axn/core/validation/validators/type_validator.rb', line 40

def self.value_matches?(value, klass:, allow_blank: false)
  # NOTE: allow mocks to pass type validation by default (much easier testing ergonomics)
  return true if Axn.config.env.test? && value.class.name&.start_with?("RSpec::Mocks::")

  case klass
  when :boolean
    [true, false].include?(value)
  when :uuid
    value.is_a?(String) && (value.blank? ? allow_blank : value.match?(/\A[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}\z/i))
  when :params
    value.is_a?(Hash) || (defined?(ActionController::Parameters) && value.is_a?(ActionController::Parameters))
  else
    value.is_a?(klass)
  end
end

Instance Method Details

#check_validity!Object

Raises:

  • (ArgumentError)


14
15
16
# File 'lib/axn/core/validation/validators/type_validator.rb', line 14

def check_validity!
  raise ArgumentError, "must supply :klass" if options[:klass].nil?
end

#validate(record) ⇒ Object

NOTE: we override the default validate method to allow for custom allow_blank logic (e.g. type: Hash should fail if given false or “”, but by default EachValidator would skip)



20
21
22
23
24
25
# File 'lib/axn/core/validation/validators/type_validator.rb', line 20

def validate(record)
  attributes.each do |attribute|
    value = record.read_attribute_for_validation(attribute)
    validate_each(record, attribute, value)
  end
end

#validate_each(record, attribute, value) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/axn/core/validation/validators/type_validator.rb', line 27

def validate_each(record, attribute, value)
  # Custom allow_blank logic: only skip validation for nil, not other blank values
  return if value.nil? && (options[:allow_nil] || options[:allow_blank])

  # Check if any of the types are valid
  valid = types.any? do |type|
    self.class.value_matches?(value, klass: type, allow_blank: options[:allow_blank])
  end

  record.errors.add attribute, (options[:message] || msg) unless valid
end