Skip to content

Instantly share code, notes, and snippets.

@cjohansen
Last active December 15, 2015 10:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjohansen/5244112 to your computer and use it in GitHub Desktop.
Save cjohansen/5244112 to your computer and use it in GitHub Desktop.
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"
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