Last active
November 17, 2017 19:59
-
-
Save mttdffy/4cb2dff596f6c186f85c to your computer and use it in GitHub Desktop.
RoR/Mongoid module for removing validations from a model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
module Unvalidate | |
extend ActiveSupport::Concern | |
module ClassMethods | |
# Removes specified validations from existing models for a given field | |
# | |
# @param [Symbol] field the field to remove validations from | |
# @param [Array<Symbol> | Symbol] validations validations to remove from field | |
# | |
# @return nil | |
# | |
def unvalidates(field, validations) | |
validations = Array(validations).map do |validation| | |
[validation, 'validator'].join('_').classify | |
end | |
_validators.reject! do |key, validators| | |
if field == key | |
validators.any? do |validator| | |
validations.include?(extract_validator_name(validator)) | |
end | |
end | |
end | |
_validate_callbacks.each do |callback| | |
if is_callback_class?(callback) && | |
callback.raw_filter.attributes.include?(field) && | |
validations.include?(extract_validator_name(callback.raw_filter)) | |
_validate_callbacks.delete(callback) | |
end | |
end | |
end | |
# Removes all validations from a given field | |
# | |
# @param [Symbol] field field to remove validations from | |
# | |
# @return nil | |
# | |
def unvalidates_all(field) | |
_validators.reject! do |key, _| | |
key == field | |
end | |
_validate_callbacks.each do |callback| | |
if is_callback_class?(callback) && | |
callback.raw_filter.attributes.include?(field) | |
_validate_callbacks.delete(callback) | |
end | |
end | |
end | |
# Removes method-based validation | |
# | |
# @param [Symbol] method name of validation method to remove | |
# | |
# @return nil | |
# | |
def unvalidate(method) | |
_validate_callbacks.each do |callback| | |
if callback.raw_filter == method | |
_validate_callbacks.delete(callback) | |
end | |
end | |
end | |
private | |
def extract_validator_name(validator) | |
validator.class.to_s.demodulize | |
end | |
def is_callback_class?(callback) | |
callback.raw_filter.respond_to?(:attributes) | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Review.class_eval do | |
include Mongoid::Unvalidate | |
unvalidates :name, :presence | |
unvalidates :email, [:presence, :uniqueness] | |
unvalidates_all :city | |
unvalidate :submitted_by_purchaser | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment