Skip to content

Commit

Permalink
Inreoduces UUID types
Browse files Browse the repository at this point in the history
This introduces a UUID typecasting option, which effectively functions as a string, but coerced to nil unless the string exactly matches the UUID pattern.

This fixes issue cgriego#174
  • Loading branch information
ekampp committed Oct 31, 2019
1 parent f0101c8 commit 4876bff
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/active_attr/typecasting.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
require "active_attr/typecasting/integer_typecaster"
require "active_attr/typecasting/object_typecaster"
require "active_attr/typecasting/string_typecaster"
require "active_attr/typecasting/uuid_typecaster"
require "active_attr/typecasting/unknown_typecaster_error"

module ActiveAttr
Expand Down Expand Up @@ -34,6 +35,7 @@ module Typecasting
Integer => IntegerTypecaster,
Object => ObjectTypecaster,
String => StringTypecaster,
UUID => UUIDTypecaster,
}.freeze

# Typecasts a value using a Class
Expand Down
32 changes: 32 additions & 0 deletions lib/active_attr/typecasting/uuid_typecaster.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
module ActiveAttr
class UUID
end

module Typecasting
# Typecasts an Object to a v4 UUID
#
# @example Usage
# UUIDTypecaster.new.call("6ed806a8-60ec-4930-ae63-9075bf37ca41") #=> "6ed806a8-60ec-4930-ae63-9075bf37ca41"
# UUIDTypecaster.new.call("6ed806a8-60ec") #=> nil
#
# @since 0.15.0
class UUIDTypecaster
# Typecasts an object to a v4 UUID
#
# Attempts to convert using SecureRandom
#
# @example Typecast a partial UUID
# typecaster.call("6ed806a8-60ec") #=> nil
#
# @param [Object, #to_s] value The object to typecast
#
# @return [String, nil] The result of typecasting
#
# @since 0.5.0
def call(value)
regex = /\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b/
value.to_s.match?(regex) ? value : nil
end
end
end
end
25 changes: 25 additions & 0 deletions spec/unit/active_attr/typecasting/uuid_typecaster_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require "spec_helper"
require "active_attr/typecasting/uuid_typecaster"

module ActiveAttr
module Typecasting
describe UUIDTypecaster do
subject(:typecaster) { described_class.new }

describe "#call" do
it "returns the original string for a UUID" do
value = "6ed806a8-60ec-4930-ae63-9075bf37ca41"
typecaster.call(value).should equal value
end

it "returns nil for an invalid UUID" do
typecaster.call("6ed806a8-60ec-4930-ae63-9075bf37").should be_nil
end

it "returns nil for nil" do
typecaster.call(nil).should be_nil
end
end
end
end
end

0 comments on commit 4876bff

Please sign in to comment.