2019-07-03 23:33:14 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module GlobalId
|
2020-07-16 14:09:35 -04:00
|
|
|
CoerceError = Class.new(ArgumentError)
|
|
|
|
|
2019-07-03 23:33:14 -04:00
|
|
|
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
|
2020-07-16 14:09:35 -04:00
|
|
|
|
|
|
|
def self.as_global_id(value, model_name: nil)
|
|
|
|
case value
|
|
|
|
when GlobalID
|
|
|
|
value
|
|
|
|
when URI::GID
|
|
|
|
GlobalID.new(value)
|
2021-01-20 10:10:29 -05:00
|
|
|
when Integer, String
|
|
|
|
raise CoerceError, "Cannot coerce #{value.class}" unless model_name.present?
|
2020-07-16 14:09:35 -04:00
|
|
|
|
|
|
|
GlobalID.new(::Gitlab::GlobalId.build(model_name: model_name, id: value))
|
|
|
|
else
|
|
|
|
raise CoerceError, "Invalid ID. Cannot coerce instances of #{value.class}"
|
|
|
|
end
|
|
|
|
end
|
2019-07-03 23:33:14 -04:00
|
|
|
end
|
|
|
|
end
|