summaryrefslogtreecommitdiff
path: root/lib/gitlab/global_id.rb
blob: 7e9412236cf49507506df2e49d4eff3e274775a4 (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
# frozen_string_literal: true

module Gitlab
  module GlobalId
    CoerceError = Class.new(ArgumentError)

    def self.build(object = nil, model_name: nil, id: nil, params: nil)
      if object
        model_name ||= object.class.name
        id ||= object.id
      end

      ::URI::GID.build(app: GlobalID.app, model_name: model_name, model_id: id, params: params)
    end

    def self.as_global_id(value, model_name: nil)
      case value
      when GlobalID
        value
      when URI::GID
        GlobalID.new(value)
      when Integer, String
        raise CoerceError, "Cannot coerce #{value.class}" unless model_name.present?

        GlobalID.new(::Gitlab::GlobalId.build(model_name: model_name, id: value))
      else
        raise CoerceError, "Invalid ID. Cannot coerce instances of #{value.class}"
      end
    end
  end
end