Created
September 16, 2011 02:01
-
-
Save davelnewton/1221010 to your computer and use it in GitHub Desktop.
Repeats validator that adds model methods
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
module Newton | |
module Validator | |
class RepeatsValidator < ActiveModel::EachValidator | |
def initialize(options) | |
@attributes = options[:attributes] | |
super | |
@how_count = options[:how_count] | |
@upto = options[:upto] | |
end | |
def setup(clazz) | |
clazz.class_eval @attributes.inject("") {|s, attr| s += <<END} | |
def #{attr}_repeats_error? | |
@#{attr}_repeats_error | |
end | |
END | |
end | |
def validate_each(record, attr, value) | |
err = false | |
if @how_count.call(record, attr, value) >= @upto | |
record.errors[attr] << (options[:message] || "repeats too much") | |
err = true | |
end | |
record.instance_variable_set "@#{attr}_repeats_error", err | |
end | |
end | |
end | |
end | |
ActiveModel::Validations.__send__(:include, Newton::Validator) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment