Last active
August 29, 2015 14:15
-
-
Save rusilko/de43471ec7f157ae0a76 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 PersonValidator < SimpleDelegator | |
include ActiveModel::Validations | |
validates :name, presence: true | |
end | |
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_class.new(record) | |
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 | |
class Person | |
include ActiveModel::Validations | |
Validator::Factory.register(self, PersonValidator) | |
validates_with Validator | |
attr_accessor :name | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment