• Stars
    star
    1,195
  • Rank 39,136 (Top 0.8 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 10 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Identify app models with a URI

Global ID - Reference models by URI

A Global ID is an app wide URI that uniquely identifies a model instance:

gid://YourApp/Some::Model/id

This is helpful when you need a single identifier to reference different classes of objects.

One example is job scheduling. We need to reference a model object rather than serialize the object itself. We can pass a Global ID that can be used to locate the model when it's time to perform the job. The job scheduler doesn't need to know the details of model naming and IDs, just that it has a global identifier that references a model.

Another example is a drop-down list of options, consisting of both Users and Groups. Normally we'd need to come up with our own ad hoc scheme to reference them. With Global IDs, we have a universal identifier that works for objects of both classes.

Usage

Mix GlobalID::Identification into any model with a #find(id) class method. Support is automatically included in Active Record.

person_gid = Person.find(1).to_global_id
# => #<GlobalID ...

person_gid.uri
# => #<URI ...

person_gid.to_s
# => "gid://app/Person/1"

GlobalID::Locator.locate person_gid
# => #<Person:0x007fae94bf6298 @id="1">

Signed Global IDs

For added security GlobalIDs can also be signed to ensure that the data hasn't been tampered with.

person_sgid = Person.find(1).to_signed_global_id
# => #<SignedGlobalID:0x007fea1944b410>

person_sgid = Person.find(1).to_sgid
# => #<SignedGlobalID:0x007fea1944b410>

person_sgid.to_s
# => "BAhJIh5naWQ6Ly9pZGluYWlkaS9Vc2VyLzM5NTk5BjoGRVQ=--81d7358dd5ee2ca33189bb404592df5e8d11420e"

GlobalID::Locator.locate_signed person_sgid
# => #<Person:0x007fae94bf6298 @id="1">

Expiration

Signed Global IDs can expire some time in the future. This is useful if there's a resource people shouldn't have indefinite access to, like a share link.

expiring_sgid = Document.find(5).to_sgid(expires_in: 2.hours, for: 'sharing')
# => #<SignedGlobalID:0x008fde45df8937 ...>

# Within 2 hours...
GlobalID::Locator.locate_signed(expiring_sgid.to_s, for: 'sharing')
# => #<Document:0x007fae94bf6298 @id="5">

# More than 2 hours later...
GlobalID::Locator.locate_signed(expiring_sgid.to_s, for: 'sharing')
# => nil

In Rails, an auto-expiry of 1 month is set by default. You can alter that deal in an initializer with:

# config/initializers/global_id.rb
Rails.application.config.global_id.expires_in = 3.months

You can assign a default SGID lifetime like so:

SignedGlobalID.expires_in = 1.month

This way any generated SGID will use that relative expiry.

It's worth noting that expiring SGIDs are not idempotent because they encode the current timestamp; repeated calls to to_sgid will produce different results. For example, in Rails

Document.find(5).to_sgid.to_s == Document.find(5).to_sgid.to_s
# => false

You need to explicitly pass expires_in: nil to generate a permanent SGID that will not expire,

# Passing a false value to either expiry option turns off expiration entirely.
never_expiring_sgid = Document.find(5).to_sgid(expires_in: nil)
# => #<SignedGlobalID:0x008fde45df8937 ...>

# Any time later...
GlobalID::Locator.locate_signed never_expiring_sgid
# => #<Document:0x007fae94bf6298 @id="5">

It's also possible to pass a specific expiry time

explicit_expiring_sgid = SecretAgentMessage.find(5).to_sgid(expires_at: Time.now.advance(hours: 1))
# => #<SignedGlobalID:0x008fde45df8937 ...>

# 1 hour later...
GlobalID::Locator.locate_signed explicit_expiring_sgid.to_s
# => nil

Note that an explicit :expires_at takes precedence over a relative :expires_in.

Purpose

You can even bump the security up some more by explaining what purpose a Signed Global ID is for. In this way evildoers can't reuse a sign-up form's SGID on the login page. For example.

signup_person_sgid = Person.find(1).to_sgid(for: 'signup_form')
# => #<SignedGlobalID:0x007fea1984b520

GlobalID::Locator.locate_signed(signup_person_sgid.to_s, for: 'signup_form')
# => #<Person:0x007fae94bf6298 @id="1">

Locating many Global IDs

When needing to locate many Global IDs use GlobalID::Locator.locate_many or GlobalID::Locator.locate_many_signed for Signed Global IDs to allow loading Global IDs more efficiently.

For instance, the default locator passes every model_id per model_name thus using model_name.where(id: model_ids) versus GlobalID::Locator.locate's model_name.find(id).

In the case of looking up Global IDs from a database, it's only necessary to query once per model_name as shown here:

gids = users.concat(people).sort_by(&:id).map(&:to_global_id)
# => [#<GlobalID:0x00007ffd6a8411a0 @uri=#<URI::GID gid://app/User/1>>,
#<GlobalID:0x00007ffd675d32b8 @uri=#<URI::GID gid://app/Student/1>>,
#<GlobalID:0x00007ffd6a840b10 @uri=#<URI::GID gid://app/User/2>>,
#<GlobalID:0x00007ffd675d2c28 @uri=#<URI::GID gid://app/Student/2>>,
#<GlobalID:0x00007ffd6a840480 @uri=#<URI::GID gid://app/User/3>>,
#<GlobalID:0x00007ffd675d2598 @uri=#<URI::GID gid://app/Student/3>>]

GlobalID::Locator.locate_many gids
# SELECT "users".* FROM "users" WHERE "users"."id" IN ($1, $2, $3)  [["id", 1], ["id", 2], ["id", 3]]
# SELECT "students".* FROM "students" WHERE "students"."id" IN ($1, $2, $3)  [["id", 1], ["id", 2], ["id", 3]]
# => [#<User id: 1>, #<Student id: 1>, #<User id: 2>, #<Student id: 2>, #<User id: 3>, #<Student id: 3>]

Note the order is maintained in the returned results.

Options

Either GlobalID::Locator.locate or GlobalID::Locator.locate_many supports a hash of options as second parameter. The supported options are:

  • :includes - A Symbol, Array, Hash or combination of them The same structure you would pass into a includes method of Active Record. See Active Record eager loading associations If present, locate or locate_many will eager load all the relationships specified here. Note: It only works if all the gids models have that relationships.
  • :only - A class, module or Array of classes and/or modules that are allowed to be located. Passing one or more classes limits instances of returned classes to those classes or their subclasses. Passing one or more modules in limits instances of returned classes to those including that module. If no classes or modules match, +nil+ is returned.
  • :ignore_missing (Only for locate_many) - By default, locate_many will call #find on the model to locate the ids extracted from the GIDs. In Active Record (and other data stores following the same pattern), #find will raise an exception if a named ID can't be found. When you set this option to true, we will use #where(id: ids) instead, which does not raise on missing records.

Custom App Locator

A custom locator can be set for an app by calling GlobalID::Locator.use and providing an app locator to use for that app. A custom app locator is useful when different apps collaborate and reference each others' Global IDs. When finding a Global ID's model, the locator to use is based on the app name provided in the Global ID url.

A custom locator can either be a block or a class.

Using a block:

GlobalID::Locator.use :foo do |gid, options|
  FooRemote.const_get(gid.model_name).find(gid.model_id)
end

Using a class:

GlobalID::Locator.use :bar, BarLocator.new
class BarLocator
  def locate(gid, options = {})
    @search_client.search name: gid.model_name, id: gid.model_id
  end
end

After defining locators as above, URIs like "gid://foo/Person/1" and "gid://bar/Person/1" will now use the foo block locator and BarLocator respectively. Other apps will still keep using the default locator.

Contributing to GlobalID

GlobalID is work of many contributors. You're encouraged to submit pull requests, propose features and discuss issues.

See CONTRIBUTING.

License

GlobalID is released under the MIT License.

More Repositories

1

rails

Ruby on Rails
Ruby
55,483
star
2

webpacker

Use Webpack to manage app-like JavaScript modules in Rails
Ruby
5,308
star
3

thor

Thor is a toolkit for building powerful command-line interfaces.
Ruby
5,115
star
4

jbuilder

Jbuilder: generate JSON objects with a Builder-style DSL
Ruby
4,324
star
5

spring

Rails application preloader
Ruby
2,804
star
6

jquery-ujs

Ruby on Rails unobtrusive scripting adapter for jQuery
JavaScript
2,607
star
7

rails-dev-box

A virtual machine for Ruby on Rails core development
Shell
2,050
star
8

solid_queue

Database-backed Active Job backend
Ruby
1,709
star
9

tailwindcss-rails

Ruby
1,388
star
10

kredis

Higher-level data structures built on Redis
Ruby
1,376
star
11

activeresource

Connects business objects and REST web services
Ruby
1,322
star
12

docked

Running Rails from Docker for easy start to development
Dockerfile
1,291
star
13

strong_parameters

Taint and required checking for Action Pack and enforcement in Active Model
Ruby
1,270
star
14

actioncable

Framework for real-time communication over websockets
1,084
star
15

importmap-rails

Use ESM with importmap to manage modern JavaScript in Rails without transpiling or bundling.
Ruby
1,037
star
16

jquery-rails

A gem to automate using jQuery with Rails
Ruby
947
star
17

sprockets

Rack-based asset packaging system
Ruby
937
star
18

sass-rails

Ruby on Rails stylesheet engine for Sass
Ruby
859
star
19

propshaft

Deliver assets for Rails
Ruby
855
star
20

exception_notification

NOTICE: official repository moved to https://github.com/smartinez87/exception_notification
Ruby
841
star
21

sdoc

Standalone sdoc generator
JavaScript
822
star
22

jsbundling-rails

Bundle and transpile JavaScript in Rails with esbuild, rollup.js, or Webpack.
Ruby
819
star
23

solid_cache

A database-backed ActiveSupport::Cache::Store
Ruby
786
star
24

rails-perftest

Benchmark and profile your Rails apps
Ruby
780
star
25

activejob

Declare job classes that can be run by a variety of queueing backends
Ruby
744
star
26

activestorage

Store files in Rails applications
734
star
27

pjax_rails

PJAX integration for Rails
Ruby
667
star
28

actioncable-examples

Action Cable Examples
Ruby
663
star
29

cache_digests

Ruby
643
star
30

sprockets-rails

Sprockets Rails integration
Ruby
575
star
31

cssbundling-rails

Bundle and process CSS in Rails with Tailwind, PostCSS, and Sass via Node.js.
Ruby
568
star
32

activerecord-session_store

Active Record's Session Store extracted from Rails
Ruby
539
star
33

execjs

Run JavaScript code from Ruby
Ruby
528
star
34

rails-observers

Rails observer (removed from core in Rails 4.0)
Ruby
516
star
35

mission_control-jobs

Dashboard and Active Job extensions to operate and troubleshoot background jobs
Ruby
491
star
36

actiontext

Edit and display rich text in Rails applications
406
star
37

request.js

JavaScript
386
star
38

acts_as_list

NOTICE: official repository moved to https://github.com/swanandp/acts_as_list
Ruby
385
star
39

marcel

Find the mime type of files, examining file, filename and declared type
Ruby
383
star
40

rubocop-rails-omakase

Omakase Ruby styling for Rails
Ruby
380
star
41

actionpack-page_caching

Static page caching for Action Pack (removed from core in Rails 4.0)
Ruby
347
star
42

commands

Run Rake/Rails commands through the console
Ruby
337
star
43

ssl_requirement

NOTICE: official repository moved to https://github.com/retr0h/ssl_requirement
Ruby
315
star
44

rails-controller-testing

Brings back `assigns` and `assert_template` to your Rails tests
Ruby
303
star
45

rails-html-sanitizer

Ruby
302
star
46

open_id_authentication

NOTICE: official repository moved to https://github.com/Velir/open_id_authentication
Ruby
285
star
47

acts_as_tree

NOTICE: official repository moved to https://github.com/amerine/acts_as_tree
Ruby
281
star
48

actionpack-action_caching

Action caching for Action Pack (removed from core in Rails 4.0)
Ruby
260
star
49

in_place_editing

NOTICE: official repository moved to https://github.com/amerine/in_place_editing
Ruby
230
star
50

protected_attributes

Protect attributes from mass-assignment in ActiveRecord models.
Ruby
229
star
51

journey

A router for rails
Ruby
221
star
52

auto_complete

NOTICE: official repository moved to https://github.com/david-kerins/auto_complete
Ruby
211
star
53

dartsass-rails

Integrate Dart Sass with the asset pipeline in Rails
Ruby
206
star
54

dynamic_form

NOTICE: official repository moved to https://github.com/joelmoss/dynamic_form
Ruby
192
star
55

solid_cable

A database backed ActionCable adapter
Ruby
187
star
56

country_select

NOTICE: official repository moved to https://github.com/stefanpenner/country_select
Ruby
176
star
57

rails-dom-testing

Extracting DomAssertions and SelectorAssertions from ActionView.
Ruby
174
star
58

routing_concerns

Abstract common routing resource concerns to cut down on duplication.
Ruby
154
star
59

esbuild-rails

Bundle and transpile JavaScript in Rails with esbuild
Ruby
147
star
60

rails-contributors

The web application that runs https://contributors.rubyonrails.org
Ruby
138
star
61

rails-new

Create Rails projects with Ruby installed
Rust
125
star
62

actionmailbox

Receive and process incoming emails in Rails
125
star
63

requestjs-rails

JavaScript
119
star
64

activemodel-globalid

Serializing models to a single string makes it easy to pass references around
Ruby
90
star
65

account_location

NOTICE: official repository moved to https://github.com/bbommarito/account_location
Ruby
73
star
66

acts_as_nested_set

NOTICE: official repository moved to https://github.com/bbommarito/acts_as_nested_set
Ruby
71
star
67

iso-3166-country-select

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
70
star
68

activerecord-deprecated_finders

Ruby
68
star
69

spring-watcher-listen

Ruby
64
star
70

website

HTML
64
star
71

weblog

Superseded by https://github.com/rails/website
HTML
63
star
72

prototype-ujs

JavaScript
62
star
73

prototype_legacy_helper

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
60
star
74

verification

NOTICE: official repository moved to https://github.com/sikachu/verification
Ruby
58
star
75

prototype-rails

Add RJS, Prototype, and Scriptaculous helpers to Rails 3.1+ apps
Ruby
55
star
76

activemodel-serializers-xml

Ruby
52
star
77

record_tag_helper

ActionView Record Tag Helpers
Ruby
51
star
78

homepage

Superseded by https://github.com/rails/website
HTML
50
star
79

rollupjs-rails

Bundle and transpile JavaScript in Rails with rollup.js
Ruby
49
star
80

actionpack-xml_parser

XML parameters parser for Action Pack (removed from core in Rails 4.0)
Ruby
49
star
81

activesupport-json_encoder

Ruby
48
star
82

etagger

Declare what goes in to your ETags: asset versions, account ID, etc.
Ruby
41
star
83

upload_progress

NOTICE: official repository moved to https://github.com/rishav/upload_progress
Ruby
39
star
84

devcontainer

Shell
38
star
85

atom_feed_helper

NOTICE: official repository moved to https://github.com/TrevorBramble/atom_feed_helper
Ruby
38
star
86

render_component

NOTICE: official repository moved to https://github.com/malev/render_component. Components allow you to call other actions for their rendered response while executing another action
Ruby
38
star
87

gsoc2014

Project website and wiki for Ruby on Rails proposals to Google Summer of Code 2014
37
star
88

gsoc2013

Project website and wiki for Ruby on Rails proposals to Google Summer of Code 2013
31
star
89

ruby-coffee-script

Ruby CoffeeScript Compiler
Ruby
28
star
90

asset_server

NOTICE: official repository moved to https://github.com/andhapp/asset_server
Ruby
27
star
91

homepage-2011

This repo is now legacy. New homepage is at rails/homepage
HTML
27
star
92

deadlock_retry

NOTICE: official repository moved to https://github.com/heaps/deadlock_retry
Ruby
27
star
93

rails-docs-server

Ruby
25
star
94

token_generator

NOTICE: official repository moved to https://github.com/bbommarito/token_generator
Ruby
25
star
95

http_authentication

NOTICE: official repository moved to https://github.com/dshimy/http_authentication
Ruby
22
star
96

irs_process_scripts

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core. The extracted inspector, reaper, and spawner scripts from script/process/*
22
star
97

javascript_test

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
JavaScript
19
star
98

buildkite-config

Fallback configuration for branches that lack a .buildkite/ directory
Ruby
18
star
99

scriptaculous_slider

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
JavaScript
18
star
100

request_profiler

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core. Request profiler based on integration test scripts
Ruby
17
star