Files
nairobi/app/models/concerns/skip_validation.rb
Javi Martín b5a4609b56 Make it easier to customize validations
There are CONSUL installations where the validations CONSUL offers by
default don't make sense because they're using a different business
logic. Removing these validations in a custom model was hard, and that's
why in many cases modifying the original CONSUL models was an easier
solution.

Since modifying the original CONSUL models makes the code harder to
maintain, we're now providing a way to easily skip validations in a
custom model. For example, in order to skip the price presence
validation in the Budget::Heading model, we could write a model in
`app/models/custom/budget/heading.rb`:

```
require_dependency Rails.root.join("app", "models", "budget", "heading").to_s

class Budget::Heading
  skip_validation :price, :presence
end
```

In order to skip validation on translatable attributes (defined with
`validates_translation`), we have to use the
`skip_translation_validation` method; for example, to skip the proposal
title presence validation:

```
require_dependency Rails.root.join("app", "models", "proposal").to_s

class Proposal
  skip_translation_validation :title, :presence
end

```

Co-Authored-By: taitus <sebastia.roig@gmail.com>
2022-03-24 17:05:35 +01:00

27 lines
875 B
Ruby

module SkipValidation
extend ActiveSupport::Concern
module ClassMethods
def skip_validation(field, validator)
validator_class = if validator.is_a?(Class)
validator
else
"ActiveModel::Validations::#{validator.to_s.camelize}Validator".constantize
end
_validators[field].reject! { |existing_validator| existing_validator.is_a?(validator_class) }
_validate_callbacks.each do |callback|
if callback.raw_filter.is_a?(validator_class)
callback.raw_filter.instance_variable_set("@attributes", callback.raw_filter.attributes - [field])
end
end
end
def skip_translation_validation(field, validator)
skip_validation(field, validator)
translation_class.skip_validation(field, validator)
end
end
end