Skip to content

Instantly share code, notes, and snippets.

@leosoto
Created August 30, 2010 15:46
Show Gist options
  • Save leosoto/557577 to your computer and use it in GitHub Desktop.
Save leosoto/557577 to your computer and use it in GitHub Desktop.
validation groups
# Hack to simulate validatable groups with Rails validations
#
# Example:
#
# class MortgageApplication < ActiveRecord::Base
# validation_group :underwriting
# validates_presence_of :ssn
# validates_presence_of :name, :if => :validating_for_underwriting?
# end
#
# MortgageApplication.new.valid? => false
# MortgageApplication.new(:ssn => "something").valid? => true
# MortgageApplication.new(:ssn => "something").valid_for_underwriting? => false
# MortgageApplication.new(:ssn => "something", :name => "foo").valid_for_underwriting? => true
module ActiveRecord::Validations::ClassMethods
def validation_group(name)
ivar_name = :"@validating_for_#{name}"
define_method(:"validating_for_#{name}?") do
instance_variable_get(ivar_name)
end
define_method(:"valid_for_#{name}?") do
instance_variable_set(ivar_name, true)
result = valid?
instance_variable_set(ivar_name, false)
result
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment