Class: SmrtLinkOptionsValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
app/validators/smrt_link_options_validator.rb

Overview

validate SmrtLinkOptions by version:

Examples:

smrt_link_option = { key: attribute_1, validations: { required: {},
                     numericality: { greater_than_equal_to: 0,
                     less_than_or_equal_to: 1}} }
ActiveModel::Validations::NumericalityValidator.new(attributes: attribute_1,
greater_than_equal_to: 0, less_than_or_equal_to: 1).validate(record)

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/validators/smrt_link_options_validator.rb', line 25

def validate(record)
  # If the version is not present no point validating
  return if record&.run&.smrt_link_version.blank?

  # Retrieve the list of smrt link options for the specified version
  record.run.smrt_link_version.smrt_link_options.each do |smrt_link_option|
    # Retrieve the list of validations
    # each one will have a key and some options
    # key is the validator name
    # options is a hash e.g. { greater_than_equal_to: 1 }
    # see the validator docs in ActiveModel for the standard ones
    smrt_link_option.validations.each do |key, options|
      validator = validator_by_prefix(key)

      # We then need to create a new instance of the validator
      # and pass the options along with the attribute name which is the key
      # of the smrt link option
      # we need to symbolize the keys as some validators do not recognise string keys
      # for options
      instance = validator.new(options.merge(attributes: smrt_link_option.key).symbolize_keys)

      # finally validate the record
      # underneath it could be validate or validates_each
      instance.validate(record)
    end
  end
end