Created
July 8, 2009 21:34
-
-
Save dstrelau/143210 to your computer and use it in GitHub Desktop.
contexts for active record validations
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
class User < ActiveRecord::Base | |
include ValidationContexts | |
validation_context :default, :signup do | |
validates_uniqueness_of :email, :allow_blank => true | |
validates_presence_of :email | |
end | |
validation_context :signup do | |
validates_confirmation_of :password | |
validates_presence_of :password_confirmation | |
validates_acceptance_of :terms, :allow_nil => false | |
end | |
validation_context :default, :if => :password_changed? do | |
validates_confirmation_of :password | |
validates_presence_of :password_confirmation | |
end | |
end |
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 ValidationContexts | |
module ClassMethods | |
# validation_context :signup {...} | |
# validation_context :default, :signup {...} | |
# validation_context :default, :if => :password_changed? {...} | |
def validation_context(*args, &block) | |
options = args.extract_options! | |
guard = proc {|obj| | |
if options[:if] && obj.respond_to?(options[:if]) | |
obj.send(options[:if]) | |
elsif options[:if].respond_to?(:call) | |
options[:if].call(obj) | |
else | |
true | |
end && args.include?(obj.validation_context) | |
} | |
with_options(:if => guard) do |o| | |
o.instance_eval(&block) | |
end | |
end | |
end | |
module InstanceMethods | |
def validation_context=(context) | |
@validation_context = context | |
end | |
def validation_context | |
@validation_context || :default | |
end | |
end | |
def self.included(receiver) | |
receiver.extend ClassMethods | |
receiver.send :include, InstanceMethods | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment