Skip to content

Instantly share code, notes, and snippets.

@gmanley
Last active December 18, 2015 22:09
Show Gist options
  • Save gmanley/5852574 to your computer and use it in GitHub Desktop.
Save gmanley/5852574 to your computer and use it in GitHub Desktop.
# app/validators/uuid_validator.rb
class UUIDValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
UUIDTools::UUID.parse_hexdigest(value)
rescue ArgumentError
UUIDTools::UUID.parse(value)
rescue ArgumentError
record.errors[attribute] << (options[:message] || "is not a valid UUID")
end
end
# spec/validators/uuid_validator_spec.rb
require 'spec_helper'
describe UUIDValidator do
let(:validator) { UUIDValidator.new({:attributes => {}}) }
let(:model) { mock("model") }
before(:each) do
model.stub("errors").and_return([])
model.errors.stub("[]").and_return({})
model.errors[].stub("<<")
end
it "should not add errors on valid uuid" do
model.should_not_receive("errors")
validator.validate_each(model, :uuid, "01234567-8901-2345-6789-012345678912")
end
it "should add errors on an invalid uuid" do
model.errors[].should_receive('<<').with("is not a valid UUID")
validator.validate_each(model, :uuid, "notvalid")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment