Last active
December 18, 2015 22:09
-
-
Save gmanley/5852574 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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