Created
February 16, 2015 14:09
-
-
Save lesniakania/04377281b39d043f40a5 to your computer and use it in GitHub Desktop.
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
class Validator < ActiveModel::Validator | |
class Factory | |
@validators = {} | |
def self.register(klass, validator) | |
@validators[klass] = validator | |
end | |
def self.build(record) | |
validator_class = @validators[record.class] | |
unless validator_class | |
fail "Validator not registered for #{record.class}" | |
end | |
validator = validator_class.new | |
validator_class.fields.each do |field| | |
validator.send("#{field}=", record.send(field)) | |
end | |
validator | |
end | |
end | |
def validate(record) | |
validator = Factory.build(record) | |
validator.valid? | |
validator.errors.each do |key, error| | |
record.errors.add(key, error) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment