Skip to content

Instantly share code, notes, and snippets.

@rakibulislam
Forked from harlow/user.rb
Created December 21, 2018 17:48
Show Gist options
  • Save rakibulislam/14ce2e56bbbabfa34be885b97db70348 to your computer and use it in GitHub Desktop.
Save rakibulislam/14ce2e56bbbabfa34be885b97db70348 to your computer and use it in GitHub Desktop.
Extract a validator in Rails. Zip code validation.
# app/models/user.rb
class User < ActiveRecord::Base
validates :zip_code, presence: true, zip_code: true
end
# app/validators/zip_code_validator.rb
class ZipCodeValidator < ActiveModel::EachValidator
ZIP_CODE_REGEX = /^\d{5}(-\d{4})?$/
def validate_each(record, attribute, value)
unless ZIP_CODE_REGEX.match value
record.errors.add(attribute, "#{value} is not a valid zip code")
end
end
end
# spec/validators/zip_code_validator_spec.rb
require 'spec_helper'
describe ZipCodeValidator, '#validate_each' do
it 'does not add errors with a valid zip code' do
record = build_record('93108')
ZipCodeValidator.new(attributes: :zip_code).validate(record)
record.errors.should be_empty
end
it 'adds errors with an invalid zip code' do
record = build_record('invalid_zip')
ZipCodeValidator.new(attributes: :zip_code).validate(record)
record.errors.full_messages.should eq [
'Zip code invalid_zip is not a valid zip code'
]
end
def build_record(zip_code)
test_class.new.tap do |object|
object.zip_code = zip_code
end
end
def test_class
Class.new do
include ActiveModel::Validations
attr_accessor :zip_code
def self.name
'TestClass'
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment