Skip to content

Instantly share code, notes, and snippets.

@marshall-lee
Created December 30, 2017 20:59
Show Gist options
  • Save marshall-lee/cfa81ca204187e9ed90d6e3c974d4441 to your computer and use it in GitHub Desktop.
Save marshall-lee/cfa81ca204187e9ed90d6e3c974d4441 to your computer and use it in GitHub Desktop.
# app/models/document.rb
class Person < ActiveRecord::Base
validate &PassportValidator
end
# lib/yoba_validator.rb
class YobaValidator < SimpleDelegator
include ActiveModel::Validations
def validate
super
errors.each do |f, e|
@delegate_sd_obj.errors.add(f, e)
end
end
def self.to_proc
kl = self
-> (obj) { kl.new(obj).validate }
end
end
# app/validators/passport_validator.rb
class PassportValidator < YobaValidator
SERIES_REGEX = /.+/
validates :passport, format: { with: SERIES_REGEX }
end
# spec/validators/passport_validator_spec.rb
require 'spec_helper'
describe PassportValidator do
subject { described_class.new(obj) }
context 'with valid series' do
let(:obj) { double(passport: 'foo') }
it { is_expected.to be_valid }
end
context 'with invalid series' do
let(:obj) { double(passport: '') }
it { is_expected.not_to be_valid }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment