Skip to content

Instantly share code, notes, and snippets.

@plukevdh
Forked from ibanez270dx/ConditionalValidations.rb
Last active August 29, 2015 14:04
Show Gist options
  • Save plukevdh/758f92577a986eced92f to your computer and use it in GitHub Desktop.
Save plukevdh/758f92577a986eced92f to your computer and use it in GitHub Desktop.
conditional validations in Rails 4+
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
class Demo < ActiveRecord::Base
include ConditionalValidations
conditionally_validate :my_field, presence: true
end
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