Forked from ibanez270dx/ConditionalValidations.rb
Last active
December 17, 2015 13:59
-
-
Save thogg4/5621626 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ConditionalValidations | |
| attr_accessor :validated_fields | |
| def field_is_required?(field) | |
| if !validated_fields.blank? | |
| validated_fields.include?(field) | |
| end | |
| end | |
| def conditionally_validate(attribute, options=nil) | |
| if !options.nil? | |
| # Passing options for built-in validators | |
| # http://guides.rubyonrails.org/active_record_validations_callbacks.html#validation-helpers | |
| if !options[:if].nil? | |
| options[:if] = "#{options[:if]} && field_is_required?(:#{attribute})" | |
| validates attribute, options | |
| else | |
| validates attribute, options.merge(if: "field_is_required?(:#{attribute})") | |
| end | |
| else | |
| # Block validation | |
| # will initiate a validator on attribute using a method called validate_#{attribute} | |
| validate :"validate_#{attribute}", if: "field_is_required?(:#{attribute})" | |
| end | |
| end | |
| end | |
| ActiveRecord::Base.extend ConditionalValidations |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment