In my pursuit to add some dynamic policy logic to my ActiveRecord models I've attempted to create a way to add instance-level validations. Has anyone had experience with this? The stuff I've searched for has been less than helpful. Here is the solution I came up with. Please critique.
# 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 >= scope.account.max_bad_logins
# scope.errors.add :bad_logins, "too many bad logins for your account policy"
# end
# }
# user.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