diff options
author | hellekin <hellekin@cepheide.org> | 2021-03-22 15:37:40 +0100 |
---|---|---|
committer | hellekin <hellekin@cepheide.org> | 2021-03-22 15:37:40 +0100 |
commit | cd49369079dfd5fc7c2530a9d601422dab26718b (patch) | |
tree | d418d041e9c0eb307ca6f25fa2c7b138a8c5147c /app/lib | |
parent | 8c015485ad2ea61d128a38e7439d8b0574adc169 (diff) | |
parent | 15096ed20f918d585f7b49610f89deefda0a20b3 (diff) | |
download | incommon-map-cd49369079dfd5fc7c2530a9d601422dab26718b.tar.gz |
Merge branch 'uuid-resolver' into main
Diffstat (limited to 'app/lib')
-rw-r--r-- | app/lib/uuid_resolver.rb | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/app/lib/uuid_resolver.rb b/app/lib/uuid_resolver.rb new file mode 100644 index 0000000..acca494 --- /dev/null +++ b/app/lib/uuid_resolver.rb @@ -0,0 +1,55 @@ +class UUIDResolver + # Note the static '4' in the third group: that's the UUID version. + UUID_V4_REGEX = %r[\A[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\z] + + attr_reader :records, :count, :record, :uuid + + def initialize(uuid) + @uuid = validate!(uuid) + @records, @count = resolve! + + end + + def record + case @count + when 0 + nil + else + records.first + end + end + + private + + # List models that have UUIDs + def public_record_types + [ + ::Agent, + ::Map, + ::Resource, + ::Taxonomy + ].freeze + end + + # Find records with this UUID + def resolve! + records = [] + + public_record_types.each do |model| + records << model.find_by(uuid: @uuid) + end + + [records.compact, records.compact.size] + end + + # Ensure the passed UUID is correct + def validate!(uuid) + validate_uuid_v4(uuid) || raise(ArgumentError.new("You must pass a valid random UUID (https://tools.ietf.org/html/rfc4122)")) + end + + # Validate a UUID version 4 (random) + def validate_uuid_v4(uuid) + uuid = uuid.to_s.downcase + uuid.match?(UUID_V4_REGEX) ? uuid : false + end +end |