Forked from ibanez270dx/ConditionalValidations.rb
Last active
August 29, 2015 14:04
-
-
Save plukevdh/758f92577a986eced92f to your computer and use it in GitHub Desktop.
conditional validations in Rails 4+
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 ConditionalValidations | |
extend ActiveSupport::Concern | |
attr_accessor :conditional_validations | |
def conditional_validations | |
@conditional_validations || [] | |
end | |
def conditionally_validate(attribute, options=nil) | |
unless options.nil? | |
# Passing options for built-in validators | |
# http://guides.rubyonrails.org/active_record_validations_callbacks.html#validation-helpers | |
unless options[:if].nil? | |
options[:if] = "#{options[:if]} && conditional_validations?(:#{attribute})" | |
validates attribute, options | |
else | |
validates attribute, options.merge(if: "conditional_validations?(:#{attribute})") | |
end | |
else | |
# Block validation | |
# will initiate a validator on attribute using a method called validate_#{attribute} | |
validate :"validate_#{attribute}", if: "conditional_validations?(:#{attribute})" | |
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
class Demo < ActiveRecord::Base | |
include ConditionalValidations | |
conditionally_validate :my_field, presence: true | |
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
d = Demo.new | |
d.valid? | |
#=> true | |
d.conditional_validations = [:my_field] | |
d.valid? | |
#=> false | |
d.my_field = "expert level" | |
d.valid? | |
#=> true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment