Created
September 4, 2013 15:43
-
-
Save zenchild/6438916 to your computer and use it in GitHub Desktop.
Extend ActiveRecord with the ability to have instance-level validations.
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
# Dan Wanek <[email protected]> | |
# 2013-09-04T15:41:31+00:0 | |
# | |
# This extension can be used to create instance-level validations. For example | |
# if you have an instance of 'user' you can do something like the following: | |
# @example: | |
# user.custom_validation ->(scope) { | |
# if scope.bad_logins >= account.max_bad_logins | |
# scope.errors.add :bad_logins, "too many bad logins for your account policy" | |
# end | |
# } | |
# account.max_bad_logins = 5 | |
# user.bad_logins = 5 | |
# user.valid? => false | |
# | |
module ActiveRecordExtension | |
module CustomValidation | |
def self.included(base) | |
base.class_eval do | |
attr_accessor :custom_validation | |
validate :run_custom_validation | |
send :include, InstanceMethods | |
end | |
end | |
module InstanceMethods | |
def run_custom_validation | |
if custom_validation | |
custom_validation.call(self) | |
else | |
true | |
end | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send :include, ActiveRecordExtension::CustomValidation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment