Skip to content

Commit 85e19f0

Browse files
♻️ Refactor global_id_column to flow through ActiveSupport's class_attribute
This simplifies the implementation's API substantially by defining both instance and class methods, and rails/globalid already depends on ActiveSupport
1 parent 11bb706 commit 85e19f0

File tree

4 files changed

+8
-16
lines changed

4 files changed

+8
-16
lines changed

lib/global_id/identification.rb

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
require "active_support/core_ext/class/attribute"
2+
13
class GlobalID
24
# Mix `GlobalID::Identification` into any model with a `#find(id)` class
35
# method. Support is automatically included in Active Record.
@@ -27,17 +29,7 @@ class GlobalID
2729
# # => #<Person:0x007fae94bf6298 @id="1">
2830
module Identification
2931
def self.included(base)
30-
base.extend(ClassMethods)
31-
end
32-
33-
module ClassMethods
34-
def global_id_column(column_name = nil)
35-
@global_id_column ||= column_name
36-
end
37-
end
38-
39-
def global_id_method
40-
self.class.global_id_column || :id
32+
base.class_attribute :global_id_column, default: :id, instance_writer: false
4133
end
4234

4335
# Returns the Global ID of the model.

lib/global_id/locator.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,10 +162,10 @@ def locate(gid, options = {})
162162
model_class = gid.model_class
163163
model_class = model_class.includes(options[:includes]) if options[:includes]
164164

165-
if model_class.global_id_column
166-
model_class.find_by model_class.global_id_column => gid.model_id
167-
else
165+
if model_class.global_id_column == :id
168166
model_class.find gid.model_id
167+
else
168+
model_class.find_by model_class.global_id_column => gid.model_id
169169
end
170170
end
171171

lib/global_id/uri/gid.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def parse(uri)
7272
#
7373
# URI::GID.create('bcx', Person.find(5), database: 'superhumans')
7474
def create(app, model, params = nil)
75-
build app: app, model_name: model.class.name, model_id: model.send(model.global_id_method), params: params
75+
build app: app, model_name: model.class.name, model_id: model.send(model.global_id_column), params: params
7676
end
7777

7878
# Create a new URI::GID from components with argument check.

test/models/configurable_key_model.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ class ConfigurableKeyModel
66

77
attr_accessor :id, :external_id
88

9-
global_id_column :external_id
9+
self.global_id_column = :external_id
1010

1111
class << self
1212
def primary_key

0 commit comments

Comments
 (0)