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
NewPersonValidator = Validator.define do | |
validates_presence_of :name | |
end | |
class Person | |
attr_accessor :name | |
def initialize(name); @name = name; end | |
end | |
person = Person.new("Frank") | |
result = NewPersonValidator.call(person) | |
puts "Valid? #{result.valid?}" #=> true | |
person = Person.new | |
result = NewPersonValidator.call(person) | |
puts "Valid? #{result.valid?}" #=> false | |
puts "Errors: #{result.errors.full_messages.join(', ')}" #=> "Errors: Name can't be blank" |
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
module Validator | |
def self.define(&block) | |
klass = Class.new do | |
include ActiveModel::Validations | |
def initialize(target) | |
@target = target | |
end | |
def method_missing(name, *args, &block) | |
@target.send(name, *args, &block) | |
end | |
def self.call(object) | |
validator = new(object) | |
validator.valid? | |
validator | |
end | |
end | |
klass.instance_eval(&block) | |
klass | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment