You can find the global id of a model with #to_global_id
:
gid = MyModel.first.to_global_id
gid.uri # => #<URI ...
gid.to_s # => "gid://..."
GlobalID::Locator.locate(gid) # => #<MyModel
The code for GlobalID
is here.
It creates a URI from the application name, model class, model id and optional params. This is done in GlobalID::URI::GID.
You can create you own GID as such:
URI::GID.create('myapp', MyModel.first, database: 'my_app_development')
# => #<URI::GID gid://myapp/MyModel/1?database=my_app_development>
The model passed must be ActiveRecord complaint, so passing a PORO (Plain Old Ruby Object) will not work:
class MyModel
end
URI::GID.create('myapp', MyModel.new)
# => NoMethodError (undefined method `id'
Let's add an id attribute:
MyModel = Struct.new(:id)
gid = URI::GID.create('myapp', MyModel.new(1))
# => #<URI::GID gid://myapp/MyModel/1>
GlobalID::Locator.locate(gid)
# => NoMethodError (undefined method `find' for MyModel:Class)
And a class method #find
:
MyModel = Struct.new(:id) do
def self.find(id)
new(id)
end
end
gid = URI::GID.create('myapp', MyModel.new(1))
GlobalID::Locator.locate(gid)
# => #<struct MyModel id="1">