Skip to content

Instantly share code, notes, and snippets.

@maier-stefan
Forked from cflipse/Post.rb
Created February 16, 2018 10:16
Show Gist options
  • Save maier-stefan/d197d4928c499f1db177407405e4dc0d to your computer and use it in GitHub Desktop.
Save maier-stefan/d197d4928c499f1db177407405e4dc0d to your computer and use it in GitHub Desktop.
External Validations using only ActiveModel
require 'delegate'
require 'active_model'
class DraftPostValidator < SimpleDelegator
include ActiveModel::Validations
validates :title, :presence => true
validate :future_publication_date
private
def errors
__getobj__.errors
end
def future_publication_date
errors.add(:publication_date, "must be in the future") if publication_date && publication_date <= Date.today
end
end
irb(main):063:0> post = Post.new
=> #<Post:0x10d196f28 @errors=#<ActiveModel::Errors:0x10d196ed8 @messages=#<OrderedHash {}>, @base=#<Post:0x10d196f28 ...>>>
irb(main):064:0> PublishedPostValidator.new(post).valid?
=> false
irb(main):065:0> post.errors.full_messages
=> ["title can't be blank", "author can't be blank"]
irb(main):070:0> post.publication_date = Date.yesterday
=> Tue, 19 Jun 2012
irb(main):071:0> DraftPostValidator.new(post).valid?
=> false
irb(main):072:0> post.errors.full_messages
=> ["title can't be blank", "publication_date must be in the future"]
irb(main):073:0>
require 'active_model'
# Most of this is the basic boilerplate described in the docs for active_model/errors; ie, the bare minimum
# a class must have to use AM::Errors
class Post
extend ActiveModel::Naming
attr_reader :errors
attr_accessor :title, :author, :publication_date
def initialize
@errors = ActiveModel::Errors.new(self)
end
def read_attribute_for_validation(attr)
send(attr)
end
def self.human_attribute_name(attr, options = {})
attr
end
def self.lookup_ancestors
[self]
end
en
# A Validator for published objects. It may have more stringent validation rules than unpublished posts.
require 'delegate'
require 'active_model'
class PublishedPostValidator < SimpleDelegator
include ActiveModel::Validations
validates :title, :presence => true
validates :author, :presence => true
validates :publication_date, :presence => true
private
def errors
__getobj__.errors
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment