Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Repeats validator that adds model methods
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