external_id 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c7f37fe1f61ae7cc606c98a516bcbf92158799383751ecfa602b3b29c32a7da2
4
+ data.tar.gz: 71a51fe88cebf3fe95516cd87c4a173d111925cdf1da6fcf3c5a8caddebc299e
5
+ SHA512:
6
+ metadata.gz: 911f2c68eff82fc94075e67f295f6c9a49324013ea9636c845705bc4d9bf8c07282d432d7cf691ca37c579b4d256a20397a7a0ef3c69abcbb1999a28d4f5ba80
7
+ data.tar.gz: 24c2e9299bb4658cda2dc0a0c0d0a805036181cf0f89096074f3fb60b831251e47be98b1e74aa97cd1e8ca250e678fecb171912d691baf5a20892d8dd8100883
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.4.7
data/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-12-02
4
+
5
+ - Initial release
6
+ - Polymorphic external ID associations for Rails models
7
+ - `ExternalId` model for database-backed storage
8
+ - `ExternalIdValue` value object for clean data handling
9
+ - `WithExternalId` concern for easy model integration
10
+ - Configurable providers with enum support
11
+ - UUID support for distributed systems
12
+ - Install generator with migration and initializer templates
13
+ - Comprehensive test suite with 46 passing examples
14
+ - Full documentation and usage examples
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Tomáš Landovský
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Tomáš Landovský
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,247 @@
1
+ # ExternalId
2
+
3
+ A Rails gem that provides a clean, polymorphic way to associate external IDs from third-party systems (like CRMs, payment processors, or any external service) with your ActiveRecord models.
4
+
5
+ ## Features
6
+
7
+ - Polymorphic associations - link external IDs to any model
8
+ - Type-safe with Rails enums for provider validation
9
+ - Value object pattern for clean external ID handling
10
+ - Unique constraints ensuring one external ID per provider per resource
11
+ - UUID support for distributed systems
12
+ - Configurable providers
13
+ - Full test coverage included
14
+
15
+ ## Installation
16
+
17
+ Add this line to your application's Gemfile:
18
+
19
+ ```ruby
20
+ gem 'external-id'
21
+ ```
22
+
23
+ Then execute:
24
+
25
+ ```bash
26
+ bundle install
27
+ ```
28
+
29
+ Run the installer:
30
+
31
+ ```bash
32
+ rails generate external_id:install
33
+ ```
34
+
35
+ This will create:
36
+ - An initializer at `config/initializers/external_id.rb`
37
+ - A migration for the `external_ids` table
38
+
39
+ Review the initializer and customize the providers, then run the migration:
40
+
41
+ ```bash
42
+ rails db:migrate
43
+ ```
44
+
45
+ ## Configuration
46
+
47
+ Edit `config/initializers/external_id.rb`:
48
+
49
+ ```ruby
50
+ ExternalId.configure do |config|
51
+ # Define your external ID providers
52
+ config.providers = [:raynet, :salesforce, :hubspot]
53
+
54
+ # Or use a hash for custom enum values
55
+ # config.providers = {
56
+ # raynet: 'raynet',
57
+ # salesforce: 'sf',
58
+ # hubspot: 'hs'
59
+ # }
60
+
61
+ # Optional: Configure base class (default: 'ActiveRecord::Base')
62
+ # config.base_class = 'ApplicationRecord'
63
+
64
+ # Optional: Use UUID for primary keys (default: true)
65
+ # config.use_uuid = true
66
+ end
67
+ ```
68
+
69
+ ## Usage
70
+
71
+ ### Include the concern in your models
72
+
73
+ ```ruby
74
+ class Customer < ApplicationRecord
75
+ include ExternalId::WithExternalId
76
+ end
77
+
78
+ class Order < ApplicationRecord
79
+ include ExternalId::WithExternalId
80
+ end
81
+ ```
82
+
83
+ ### Add an external ID to a record
84
+
85
+ ```ruby
86
+ customer = Customer.find(123)
87
+
88
+ # Option 1: Using keyword arguments
89
+ customer.add_external_id(provider: 'raynet', id: 'R-12345')
90
+
91
+ # Option 2: Using an ExternalIdValue object
92
+ external_id = ExternalId::ExternalIdValue.new(provider: 'salesforce', id: 'SF-67890')
93
+ customer.add_external_id(external_id)
94
+ ```
95
+
96
+ ### Find a record by external ID
97
+
98
+ ```ruby
99
+ # Find customer by their Raynet ID
100
+ customer = Customer.find_by_external_id('raynet', 'R-12345')
101
+
102
+ # Returns nil if not found
103
+ customer = Customer.find_by_external_id('raynet', 'nonexistent') # => nil
104
+
105
+ # Raises ArgumentError for unknown providers
106
+ Customer.find_by_external_id('unknown', '123') # => ArgumentError
107
+ ```
108
+
109
+ ### Get the external ID from a record
110
+
111
+ ```ruby
112
+ customer = Customer.find(123)
113
+
114
+ # Returns an ExternalIdValue object
115
+ external_id = customer.external_id
116
+
117
+ if external_id.present?
118
+ puts external_id.provider # => 'raynet'
119
+ puts external_id.id # => 'R-12345'
120
+ puts external_id.to_s # => 'raynet:R-12345'
121
+ puts external_id.to_hash # => { provider: 'raynet', id: 'R-12345' }
122
+ end
123
+
124
+ # Blank when no external ID exists
125
+ customer_without_eid = Customer.create(name: 'Test')
126
+ customer_without_eid.external_id.blank? # => true
127
+ ```
128
+
129
+ ### Access the underlying ActiveRecord model
130
+
131
+ ```ruby
132
+ customer = Customer.find(123)
133
+
134
+ # Access the external_id record directly
135
+ customer.eid # => ExternalId::ExternalId instance or nil
136
+
137
+ # The association is dependent: :destroy
138
+ # Deleting the customer will also delete the external_id
139
+ ```
140
+
141
+ ## Database Schema
142
+
143
+ The gem creates an `external_ids` table with the following structure:
144
+
145
+ ```ruby
146
+ create_table :external_ids, id: :uuid do |t|
147
+ t.string :provider, null: false, index: true
148
+ t.string :external_id, null: false
149
+ t.references :resource, polymorphic: true, null: false, index: true, type: :uuid
150
+
151
+ t.timestamps
152
+ end
153
+
154
+ add_index :external_ids, [:provider, :resource_type, :resource_id],
155
+ unique: true, name: 'index_one_external_id_per_resource'
156
+ ```
157
+
158
+ This ensures that each resource can only have one external ID per provider.
159
+
160
+ ## ExternalIdValue
161
+
162
+ The `ExternalIdValue` class is a value object that provides a clean interface for working with external IDs:
163
+
164
+ ```ruby
165
+ # Create a value object
166
+ eid = ExternalId::ExternalIdValue.new(provider: 'raynet', id: '12345')
167
+
168
+ # Check presence
169
+ eid.present? # => true
170
+ eid.blank? # => false
171
+
172
+ # String representation
173
+ eid.to_s # => 'raynet:12345'
174
+
175
+ # Hash representation
176
+ eid.to_hash # => { provider: 'raynet', id: '12345' }
177
+
178
+ # Array representation
179
+ eid.to_a # => ['raynet', '12345']
180
+
181
+ # Create from array
182
+ ExternalId::ExternalIdValue.from_array(['raynet', '12345'])
183
+
184
+ # Create blank value
185
+ ExternalId::ExternalIdValue.blank # => blank instance
186
+
187
+ # Comparison
188
+ eid1 = ExternalId::ExternalIdValue.new(provider: 'raynet', id: '123')
189
+ eid2 = ExternalId::ExternalIdValue.new(provider: 'raynet', id: '123')
190
+ eid1 == eid2 # => true
191
+ ```
192
+
193
+ ## Advanced Usage
194
+
195
+ ### Custom scopes
196
+
197
+ You can add custom scopes to query external IDs:
198
+
199
+ ```ruby
200
+ # In your application
201
+ class ApplicationRecord < ActiveRecord::Base
202
+ primary_abstract_class
203
+ end
204
+
205
+ # Add custom scopes
206
+ class ExternalId::ExternalId
207
+ scope :raynet, -> { where(provider: 'raynet') }
208
+ scope :customers, -> { where(resource_type: 'Customer') }
209
+ end
210
+
211
+ # Use them
212
+ ExternalId::ExternalId.raynet.customers
213
+ ```
214
+
215
+ ### Handling multiple providers
216
+
217
+ ```ruby
218
+ customer = Customer.find(123)
219
+
220
+ # Add IDs from different providers
221
+ customer.add_external_id(provider: 'raynet', id: 'R-12345')
222
+
223
+ # This will fail due to unique constraint (one ID per provider per resource)
224
+ customer.add_external_id(provider: 'raynet', id: 'R-99999') # => ActiveRecord::RecordNotUnique
225
+
226
+ # But you can have the same customer in different systems
227
+ # by using a different provider (requires updating the resource)
228
+ # Note: Currently limited to one external_id per resource
229
+ ```
230
+
231
+ ## Development
232
+
233
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
234
+
235
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
236
+
237
+ ## Contributing
238
+
239
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/external-id. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/external-id/blob/main/CODE_OF_CONDUCT.md).
240
+
241
+ ## License
242
+
243
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
244
+
245
+ ## Code of Conduct
246
+
247
+ Everyone interacting in the External::Id project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/external-id/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ExternalId
4
+ module WithExternalId
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ has_one :eid, class_name: 'ExternalId::ExternalId', as: :resource, dependent: :destroy
9
+ end
10
+
11
+ class_methods do
12
+ def find_by_external_id(provider, external_id)
13
+ providers = ::ExternalId.configuration.providers
14
+ unless providers.key?(provider.to_sym)
15
+ raise ArgumentError,
16
+ "Provider must be one of #{providers.keys}, was '#{provider}'"
17
+ end
18
+
19
+ ::ExternalId::ExternalId.find_by(provider: provider, external_id: external_id, resource_type: name)&.resource
20
+ end
21
+ end
22
+
23
+ def add_external_id(external_id_object = nil, provider: nil, id: nil)
24
+ if external_id_object.blank? && provider.blank? && id.blank?
25
+ raise 'Either ExternalIdValue or provider and id are required'
26
+ end
27
+
28
+ eid = external_id_object.is_a?(::ExternalId::ExternalIdValue) ? external_id_object : ::ExternalId::ExternalIdValue.new(provider: provider, id: id)
29
+
30
+ ::ExternalId::ExternalId.find_or_create_by!(provider: eid.provider, external_id: eid.id, resource: self)
31
+ end
32
+
33
+ def external_id
34
+ ::ExternalId::ExternalIdValue.from_model(eid)
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ExternalId
4
+ class Configuration
5
+ attr_accessor :providers, :base_class, :use_uuid
6
+
7
+ def initialize
8
+ @providers = {}
9
+ @base_class = 'ActiveRecord::Base'
10
+ @use_uuid = true
11
+ end
12
+
13
+ def providers=(value)
14
+ if value.is_a?(Array)
15
+ # Convert array to hash format expected by enum
16
+ @providers = value.each_with_object({}) { |provider, hash| hash[provider.to_sym] = provider.to_s }
17
+ elsif value.is_a?(Hash)
18
+ @providers = value
19
+ else
20
+ raise ArgumentError, 'providers must be an Array or Hash'
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ExternalId
4
+ class ExternalId < ActiveRecord::Base
5
+ self.table_name = 'external_ids'
6
+
7
+ belongs_to :resource, polymorphic: true
8
+
9
+ validates :provider, presence: true
10
+ validates :external_id, presence: true
11
+
12
+ before_create :set_id_if_needed
13
+
14
+ private
15
+
16
+ def set_id_if_needed
17
+ return unless id.nil? && ::ExternalId.configuration.use_uuid
18
+
19
+ self.id = SecureRandom.uuid
20
+ end
21
+
22
+ public
23
+
24
+ # Define enum dynamically based on configuration
25
+ def self.providers
26
+ @providers ||= ::ExternalId.configuration.providers
27
+ end
28
+
29
+ # Set up enum if providers are configured
30
+ def self.setup_enum!
31
+ return if providers.empty?
32
+
33
+ enum :provider, providers, prefix: true
34
+ end
35
+
36
+ # Call setup when the class is loaded
37
+ def self.inherited(subclass)
38
+ super
39
+ subclass.setup_enum! if subclass == ExternalId::ExternalId
40
+ end
41
+ end
42
+ end
43
+
44
+ # Setup enum after configuration
45
+ ExternalId::ExternalId.setup_enum! if defined?(Rails) && Rails.application
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ExternalId
4
+ # ExternalId value object
5
+ class ExternalIdValue
6
+ include ActiveModel::Model
7
+ include ActiveModel::Attributes
8
+
9
+ attr_accessor :provider, :id
10
+
11
+ validates :provider, presence: true
12
+ validates :id, presence: true
13
+
14
+ def self.blank
15
+ new
16
+ end
17
+
18
+ # Create from ExternalId model
19
+ def self.from_model(external_id_model)
20
+ return blank if external_id_model.blank?
21
+
22
+ new(
23
+ provider: external_id_model.provider,
24
+ id: external_id_model.external_id
25
+ )
26
+ end
27
+
28
+ # Create from array format [provider, id]
29
+ def self.from_array(array)
30
+ return blank if array.blank? || !array.is_a?(Array) || array.size != 2
31
+
32
+ provider, id = array
33
+
34
+ new(provider: provider, id: id)
35
+ end
36
+
37
+ def initialize(provider: nil, id: nil)
38
+ @provider = provider.present? ? provider.to_s : provider
39
+ @id = id.present? ? id.to_s : id
40
+ end
41
+
42
+ def present?
43
+ provider.present? && id.present?
44
+ end
45
+
46
+ def blank?
47
+ !present?
48
+ end
49
+
50
+ def ==(other)
51
+ return false unless other.is_a?(ExternalIdValue)
52
+
53
+ provider == other.provider && id == other.id
54
+ end
55
+
56
+ def to_s
57
+ return '' if blank?
58
+
59
+ "#{provider}:#{id}"
60
+ end
61
+
62
+ def to_hash
63
+ return {} if blank?
64
+
65
+ {
66
+ provider: provider,
67
+ id: id
68
+ }
69
+ end
70
+
71
+ # Alias for compatibility
72
+ alias_method :attributes, :to_hash
73
+
74
+ def to_a
75
+ return [] if blank?
76
+
77
+ [provider, id]
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ExternalId
4
+ class Railtie < Rails::Railtie
5
+ initializer 'external_id.active_record' do
6
+ ActiveSupport.on_load(:active_record) do
7
+ # Make the concern available to all ActiveRecord models
8
+ # Users will still need to explicitly include it
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ExternalId
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record'
4
+ require 'active_support'
5
+
6
+ require_relative 'external_id/version'
7
+ require_relative 'external_id/configuration'
8
+ require_relative 'external_id/models/external_id_value'
9
+ require_relative 'external_id/models/external_id'
10
+ require_relative 'external_id/concerns/with_external_id'
11
+
12
+ module ExternalId
13
+ class << self
14
+ attr_writer :configuration
15
+
16
+ def configuration
17
+ @configuration ||= Configuration.new
18
+ end
19
+
20
+ def configure
21
+ yield(configuration)
22
+ end
23
+
24
+ def reset_configuration!
25
+ @configuration = Configuration.new
26
+ end
27
+ end
28
+ end
29
+
30
+ require 'external_id/railtie' if defined?(Rails::Railtie)
@@ -0,0 +1,34 @@
1
+ ===============================================================================
2
+
3
+ ExternalId has been installed!
4
+
5
+ Next steps:
6
+
7
+ 1. Review and customize the configuration in:
8
+ config/initializers/external_id.rb
9
+
10
+ 2. Run the migration to create the external_ids table:
11
+ rails db:migrate
12
+
13
+ 3. Include the concern in your models:
14
+
15
+ class Customer < ApplicationRecord
16
+ include ExternalId::WithExternalId
17
+ end
18
+
19
+ 4. Start using external IDs in your application:
20
+
21
+ # Add an external ID to a record
22
+ customer.add_external_id(provider: 'raynet', id: '12345')
23
+
24
+ # Find a record by external ID
25
+ customer = Customer.find_by_external_id('raynet', '12345')
26
+
27
+ # Get the external ID value object
28
+ external_id = customer.external_id
29
+ external_id.provider # => 'raynet'
30
+ external_id.id # => '12345'
31
+
32
+ For more information, see: https://github.com/yourusername/external-id
33
+
34
+ ===============================================================================
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ ExternalId.configure do |config|
4
+ # Define the external ID providers your application will use
5
+ # You can pass an array of symbols or a hash for enum configuration
6
+ config.providers = [:raynet]
7
+
8
+ # Optionally, use a hash to customize the enum values:
9
+ # config.providers = {
10
+ # raynet: 'raynet',
11
+ # salesforce: 'salesforce',
12
+ # hubspot: 'hubspot'
13
+ # }
14
+
15
+ # Configure the base class for the ExternalId model
16
+ # Default: 'ActiveRecord::Base'
17
+ # Change this if you have a custom base class like ApplicationRecord or ApplicationResource
18
+ # config.base_class = 'ApplicationRecord'
19
+
20
+ # Use UUID for primary keys (recommended for distributed systems)
21
+ # Default: true
22
+ # config.use_uuid = true
23
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateExternalIds < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
4
+ def change
5
+ create_table :external_ids<%= ', id: :uuid' if ExternalId.configuration.use_uuid %> do |t|
6
+ t.string :provider, null: false, index: true
7
+ t.string :external_id, null: false
8
+ t.references :resource, polymorphic: true, null: false, index: true<%= ', type: :uuid' if ExternalId.configuration.use_uuid %>
9
+
10
+ t.timestamps
11
+ end
12
+
13
+ # One resource can have only one external id per provider
14
+ add_index :external_ids, %i[provider resource_type resource_id], unique: true,
15
+ name: 'index_one_external_id_per_resource'
16
+ end
17
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/generators'
4
+ require 'rails/generators/active_record'
5
+
6
+ module ExternalId
7
+ module Generators
8
+ class InstallGenerator < Rails::Generators::Base
9
+ include ActiveRecord::Generators::Migration
10
+
11
+ source_root File.expand_path('install/templates', __dir__)
12
+
13
+ desc 'Creates ExternalId initializer and migration'
14
+
15
+ def copy_initializer
16
+ template 'initializer.rb', 'config/initializers/external_id.rb'
17
+ end
18
+
19
+ def create_migration
20
+ migration_template 'migration.rb.tt', File.join(db_migrate_path, 'create_external_ids.rb')
21
+ end
22
+
23
+ def show_readme
24
+ readme 'README' if behavior == :invoke
25
+ end
26
+
27
+ private
28
+
29
+ def db_migrate_path
30
+ if defined?(Rails.application) && Rails.application.config.paths['db/migrate']
31
+ Rails.application.config.paths['db/migrate'].to_a.first
32
+ else
33
+ 'db/migrate'
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,113 @@
1
+ # Type signatures for external_id gem
2
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
3
+
4
+ # Stub declarations for Rails/ActiveRecord dependencies
5
+ module ActiveModel
6
+ module Model
7
+ end
8
+
9
+ module Attributes
10
+ end
11
+ end
12
+
13
+ module ActiveSupport
14
+ module Concern
15
+ end
16
+ end
17
+
18
+ module ActiveRecord
19
+ class Base
20
+ end
21
+ end
22
+
23
+ module Rails
24
+ class Railtie
25
+ end
26
+ end
27
+
28
+ module ExternalId
29
+ VERSION: String
30
+
31
+ # Module-level configuration methods
32
+ def self.configuration: () -> Configuration
33
+ def self.configuration=: (Configuration) -> Configuration
34
+ def self.configure: () { (Configuration) -> void } -> void
35
+ def self.reset_configuration!: () -> Configuration
36
+
37
+ # Configuration class for the gem
38
+ class Configuration
39
+ attr_reader providers: Hash[Symbol, String]
40
+ attr_accessor base_class: String
41
+ attr_accessor use_uuid: bool
42
+
43
+ def initialize: () -> void
44
+ def providers=: (Array[String | Symbol] | Hash[Symbol, String]) -> Hash[Symbol, String]
45
+ end
46
+
47
+ # Value object for external IDs
48
+ class ExternalIdValue
49
+ include ActiveModel::Model
50
+ include ActiveModel::Attributes
51
+
52
+ attr_accessor provider: String?
53
+ attr_accessor id: String?
54
+
55
+ def self.blank: () -> ExternalIdValue
56
+ def self.from_model: (ExternalId?) -> ExternalIdValue
57
+ def self.from_array: (Array[String?]?) -> ExternalIdValue
58
+
59
+ def initialize: (?provider: String? | Symbol?, ?id: String?) -> void
60
+ def present?: () -> bool
61
+ def blank?: () -> bool
62
+ def ==: (untyped) -> bool
63
+ def to_s: () -> String
64
+ def to_hash: () -> Hash[Symbol, String?]
65
+ def attributes: () -> Hash[Symbol, String?]
66
+ def to_a: () -> Array[String?]
67
+ end
68
+
69
+ # ActiveRecord model for storing external IDs
70
+ class ExternalId < ActiveRecord::Base
71
+ # Associations
72
+ def resource: () -> ActiveRecord::Base?
73
+ def resource=: (ActiveRecord::Base?) -> ActiveRecord::Base?
74
+
75
+ # Attributes
76
+ def provider: () -> String?
77
+ def provider=: (String?) -> String?
78
+ def external_id: () -> String?
79
+ def external_id=: (String?) -> String?
80
+ def resource_type: () -> String?
81
+ def resource_type=: (String?) -> String?
82
+ def resource_id: () -> (String | Integer)?
83
+ def resource_id=: ((String | Integer)?) -> (String | Integer)?
84
+
85
+ # Class methods
86
+ def self.providers: () -> Hash[Symbol, String]
87
+ def self.setup_enum!: () -> void
88
+
89
+ private
90
+
91
+ def set_id_if_needed: () -> void
92
+ end
93
+
94
+ # Concern module for adding external ID support to models
95
+ module WithExternalId
96
+ extend ActiveSupport::Concern
97
+
98
+ # Instance methods available to including classes
99
+ def eid: () -> ExternalId?
100
+ def eid=: (ExternalId?) -> ExternalId?
101
+ def add_external_id: (?ExternalIdValue?, ?provider: String? | Symbol?, ?id: String?) -> ExternalId
102
+ def external_id: () -> ExternalIdValue
103
+
104
+ # Class methods added to including classes
105
+ module ClassMethods
106
+ def find_by_external_id: (String | Symbol, String) -> ActiveRecord::Base?
107
+ end
108
+ end
109
+
110
+ # Rails Railtie for integration
111
+ class Railtie < Rails::Railtie
112
+ end
113
+ end
metadata ADDED
@@ -0,0 +1,178 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: external_id
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Tomáš Landovský
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: activerecord
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '6.0'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '9.0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '6.0'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '9.0'
32
+ - !ruby/object:Gem::Dependency
33
+ name: activesupport
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - ">="
37
+ - !ruby/object:Gem::Version
38
+ version: '6.0'
39
+ - - "<"
40
+ - !ruby/object:Gem::Version
41
+ version: '9.0'
42
+ type: :runtime
43
+ prerelease: false
44
+ version_requirements: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '6.0'
49
+ - - "<"
50
+ - !ruby/object:Gem::Version
51
+ version: '9.0'
52
+ - !ruby/object:Gem::Dependency
53
+ name: railties
54
+ requirement: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: '6.0'
59
+ - - "<"
60
+ - !ruby/object:Gem::Version
61
+ version: '9.0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '6.0'
69
+ - - "<"
70
+ - !ruby/object:Gem::Version
71
+ version: '9.0'
72
+ - !ruby/object:Gem::Dependency
73
+ name: rspec
74
+ requirement: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - "~>"
77
+ - !ruby/object:Gem::Version
78
+ version: '3.0'
79
+ type: :development
80
+ prerelease: false
81
+ version_requirements: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - "~>"
84
+ - !ruby/object:Gem::Version
85
+ version: '3.0'
86
+ - !ruby/object:Gem::Dependency
87
+ name: rspec-rails
88
+ requirement: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - "~>"
91
+ - !ruby/object:Gem::Version
92
+ version: '6.0'
93
+ type: :development
94
+ prerelease: false
95
+ version_requirements: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - "~>"
98
+ - !ruby/object:Gem::Version
99
+ version: '6.0'
100
+ - !ruby/object:Gem::Dependency
101
+ name: sqlite3
102
+ requirement: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - "~>"
105
+ - !ruby/object:Gem::Version
106
+ version: '2.1'
107
+ type: :development
108
+ prerelease: false
109
+ version_requirements: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - "~>"
112
+ - !ruby/object:Gem::Version
113
+ version: '2.1'
114
+ - !ruby/object:Gem::Dependency
115
+ name: factory_bot
116
+ requirement: !ruby/object:Gem::Requirement
117
+ requirements:
118
+ - - "~>"
119
+ - !ruby/object:Gem::Version
120
+ version: '6.0'
121
+ type: :development
122
+ prerelease: false
123
+ version_requirements: !ruby/object:Gem::Requirement
124
+ requirements:
125
+ - - "~>"
126
+ - !ruby/object:Gem::Version
127
+ version: '6.0'
128
+ description: A Rails gem that provides a clean way to associate external IDs from
129
+ third-party systems with your ActiveRecord models using polymorphic associations.
130
+ email:
131
+ - landovsky@gmail.com
132
+ executables: []
133
+ extensions: []
134
+ extra_rdoc_files: []
135
+ files:
136
+ - ".ruby-version"
137
+ - CHANGELOG.md
138
+ - CODE_OF_CONDUCT.md
139
+ - LICENSE
140
+ - LICENSE.txt
141
+ - README.md
142
+ - Rakefile
143
+ - lib/external_id.rb
144
+ - lib/external_id/concerns/with_external_id.rb
145
+ - lib/external_id/configuration.rb
146
+ - lib/external_id/models/external_id.rb
147
+ - lib/external_id/models/external_id_value.rb
148
+ - lib/external_id/railtie.rb
149
+ - lib/external_id/version.rb
150
+ - lib/generators/external_id/install/templates/README
151
+ - lib/generators/external_id/install/templates/initializer.rb
152
+ - lib/generators/external_id/install/templates/migration.rb.tt
153
+ - lib/generators/external_id/install_generator.rb
154
+ - sig/external_id.rbs
155
+ homepage: https://github.com/landovsky/external-id-gem
156
+ licenses:
157
+ - MIT
158
+ metadata:
159
+ source_code_uri: https://github.com/landovsky/external-id-gem
160
+ changelog_uri: https://github.com/landovsky/external-id-gem/blob/main/CHANGELOG.md
161
+ rdoc_options: []
162
+ require_paths:
163
+ - lib
164
+ required_ruby_version: !ruby/object:Gem::Requirement
165
+ requirements:
166
+ - - ">="
167
+ - !ruby/object:Gem::Version
168
+ version: 2.7.0
169
+ required_rubygems_version: !ruby/object:Gem::Requirement
170
+ requirements:
171
+ - - ">="
172
+ - !ruby/object:Gem::Version
173
+ version: '0'
174
+ requirements: []
175
+ rubygems_version: 3.6.9
176
+ specification_version: 4
177
+ summary: Polymorphic external ID associations for Rails models
178
+ test_files: []