Skip to content

Instantly share code, notes, and snippets.

@rusilko
Last active August 29, 2015 14:15
Show Gist options
  • Save rusilko/de43471ec7f157ae0a76 to your computer and use it in GitHub Desktop.
Save rusilko/de43471ec7f157ae0a76 to your computer and use it in GitHub Desktop.
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