Created
August 30, 2010 15:46
-
-
Save leosoto/557577 to your computer and use it in GitHub Desktop.
validation groups
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
# 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