aboutsummaryrefslogtreecommitdiff
path: root/app/lib/uuid_resolver.rb
blob: acca494bc9cb6401a445264db70bbcdabaf75d0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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