Skip to content

Instantly share code, notes, and snippets.

@davelnewton
Created September 16, 2011 02:01
Show Gist options
  • Save davelnewton/1221010 to your computer and use it in GitHub Desktop.
Save davelnewton/1221010 to your computer and use it in GitHub Desktop.
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