exid 0.1.0 → 0.1.1

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2aab9d8df36bc997b6839fb83b61ddc6d39d8a10ff9a3b4d7c54277e942d067c
4
- data.tar.gz: 369a55471d75be3be5f57c8ed5a7c4a29816323327fb82451ed100d61de6879f
3
+ metadata.gz: e0b51f276cf5b4bac2e662b192b8410ce19c76e04aa93e1b4b6daa58fba00ddb
4
+ data.tar.gz: 4bf5b946a071e7eec2ce02f7bda93089f514f18daa1a858a58585952eea7c153
5
5
  SHA512:
6
- metadata.gz: ebc8666f8a20f549ae7b8abefb1d82d8fa4a0a87c1d7c6455966190d3e9517fc502966637fe8a3ccc1be68060fb91e85d9c17b02992594481bb211d98a5f7599
7
- data.tar.gz: 63ba0300682c8c6682811bec56cc7ba40db7d1f4dcf3a61d465171dd126a6ca2d9c99292bbdf2a0a3be3464802f4848b199190452317c6767bef99ba63d8c014
6
+ metadata.gz: 472e3a02ace26c1dd4acbf0109a3033f7273312fde90370bcbbe560416293e8bc51178c6c3859d31d4c46ee1c580f41213137091803c3a5f8d82630733f430ec
7
+ data.tar.gz: e8cec05ea307a1c28479135758b5705b0b5fd993a2aa6ee51f937e1fb6ba79a947c5b810487b6027de9a8639dea5e05da9ad479222bfe2c62c890391f492d0dc
data/README.md CHANGED
@@ -1,43 +1,84 @@
1
1
  # Exid
2
2
 
3
- TODO: Delete this and the text below, and describe your gem
3
+ **!! Warning: Documentation is not complete yet. Work in progress**
4
4
 
5
- Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/exid`. To experiment with that code, run `bin/console` for an interactive prompt.
5
+ This gem implements helper methods for implementing External, Prefixed
6
+ identifiers for records.
6
7
 
7
- ## Installation
8
+ Core `Exid::Coder.encode` accepts a string prefix with an UUID and
9
+ returns an "external ID", composed of this prefix and zero-padded
10
+ Base62-encoded UUID.
8
11
 
9
- TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
12
+ For example: `prg, 018977bb-02f0-729c-8c00-2f384eccb763` => `prg_02TOxMzOS0VaLzYiS3NPd9`
10
13
 
11
- Install the gem and add to the application's Gemfile by executing:
14
+ See more:
15
+ - https://dev.to/stripe/designing-apis-for-humans-object-ids-3o5a
16
+ - https://danschultzer.com/posts/prefixed-base62-uuidv7-object-ids-with-ecto
17
+ - https://dev.to/drnic/friendly-ids-for-ruby-on-rails-1c8p
18
+ - https://github.com/excid3/prefixed_ids
19
+ - https://github.com/sprql/uuid7-ruby
20
+ - https://github.com/steventen/base62-rb
12
21
 
13
- ```bash
14
- bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
22
+ ## Usage
23
+
24
+ Add a UUID or (preferably) UUIDv7 to your model include a helper module. Pass a
25
+ prefix (String) and a field name (Symbol) to the `Exid::Record.new` method.
26
+
27
+ ```ruby
28
+ class User < ApplicationRecord
29
+ include Exid::Record.new("user", :uuid)
30
+
31
+ # Optional, but recommended. Use the Exid value as the primary object
32
+ # identier.
33
+
34
+ def to_param = prefix_eid_value
35
+ end
15
36
  ```
16
37
 
17
- If bundler is not being used to manage dependencies, install the gem by executing:
38
+ That's all. This will add certain class and instance methods to your object.
18
39
 
19
- ```bash
20
- gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
40
+ ```ruby
41
+ user = User.create!(uuid: "018977bb-02f0-729c-8c00-2f384eccb763")
21
42
  ```
22
43
 
23
- ## Usage
44
+ Following methods are now available on the instance class.
45
+
46
+ ```ruby
47
+ user.prefix_eid_value # => "user_02TOxMzOS0VaLzYiS3NPd9"
24
48
 
25
- TODO: Write usage instructions here
49
+ user.prefix_eid_prefix_name # => "user"
26
50
 
27
- ## Development
51
+ user.prefix_eid_field # => :uuid
52
+ ```
28
53
 
29
- 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.
54
+ The `prefix_eid_handle` instanec method simply returns last 10 characters of
55
+ identifier. This might be useful for displaying in the UI as distinguishing
56
+ identifier. If the UUID7 is used as the identifier, the first few characters
57
+ are not random. They come from the timestamp, so they will be the same for most
58
+ objects created at the same time. Pass integer as the argument to get the last
59
+ N characters.
30
60
 
31
- 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).
61
+ ```ruby
62
+ user.prefix_eid_handle # => "OBtqZqRhLm"
32
63
 
33
- ## Contributing
64
+ user.prefix_eid_handle(6) # => "ZqRhLm"
65
+ ```
34
66
 
35
- Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/exid. 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]/exid/blob/main/CODE_OF_CONDUCT.md).
67
+ The `Exid::Record` also offers couple of instance methods designed load
68
+ records. This is another way to mimic Rails `GlobalID`. Warning: Steer
69
+ away from using this as default way to load records using user supplied
70
+ identifiers. User might replace the identifier with other record which might
71
+ lead to unexpected results and security issues.
36
72
 
37
- ## License
73
+ The `fetch` class method will return the record or nil if not found. The
74
+ `fetch!` variant will use Rails 7.1+ `sole` under the hood and raise an
75
+ exception if the record is not found (or if more than one record is found).
38
76
 
39
- The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
77
+ ```ruby
78
+ Exid::Record.fetch!("pref_02WoeojY8dqVYcAhs321rm")
79
+ Exid::Record.fetch("pref_02WoeojY8dqVYcAhs321rm")
80
+ ```
40
81
 
41
- ## Code of Conduct
82
+ ## License
42
83
 
43
- Everyone interacting in the Exid project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/exid/blob/main/CODE_OF_CONDUCT.md).
84
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Exid
4
+ class Base62
5
+ CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
6
+ BASE = CHARS.length
7
+ CHARS_HASH = CHARS.each_char.zip(0...BASE).to_h
8
+ MAX_LENGTH = 22
9
+
10
+ def self.encode(num)
11
+ result =
12
+ (1..).reduce("") do |acc, _|
13
+ break acc unless num.positive?
14
+
15
+ num, remainder = num.divmod(BASE)
16
+ CHARS[remainder] + acc
17
+ end
18
+
19
+ result.rjust(MAX_LENGTH, "0")
20
+ end
21
+
22
+ def self.decode(str)
23
+ max = str.length - 1
24
+ str.each_char.zip(0..max).reduce(0) do |acc, (char, index)|
25
+ acc + (CHARS_HASH[char] * (BASE**(max - index)))
26
+ end
27
+ end
28
+ end
29
+ end
data/lib/exid/coder.rb ADDED
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This class gets a string prefix and an UUID and returns an "external ID",
4
+ # composed of this prefix and zero-padded Base62-encoded UUID. For example:
5
+ # prg, 018977bb-02f0-729c-8c00-2f384eccb763 => prg_02TOxMzOS0VaLzYiS3NPd9
6
+
7
+ # FIXME: 2025-05-20 - This is not very efficient, as the performance was
8
+ # not a concern when this was written. There is lots of string operations
9
+ # while encoding/decoding, which could be replaced by number operations.
10
+ # At this point it is not worth the effort, as the performance is not
11
+ # critical. It can encode around 100k/s and decode 50k/s on my laptop.
12
+
13
+ # This could be a value objet, which could return various representations,
14
+ # including the timestamp, the UUID, the prefix, or the object itself. For now
15
+ # this is just a quick experiment to see where we go from here.
16
+ #
17
+ # See more:
18
+ # - https://dev.to/stripe/designing-apis-for-humans-object-ids-3o5a
19
+ # - https://danschultzer.com/posts/prefixed-base62-uuidv7-object-ids-with-ecto
20
+ # - https://dev.to/drnic/friendly-ids-for-ruby-on-rails-1c8p
21
+ # - https://github.com/excid3/prefixed_ids
22
+ # - https://github.com/sprql/uuid7-ruby
23
+ # - https://github.com/steventen/base62-rb
24
+
25
+ module Exid
26
+ class DecodeError < StandardError; end
27
+
28
+ Result = Data.define(:prefix, :uuid) do
29
+ def deconstruct = [prefix, uuid]
30
+ end
31
+
32
+ module Coder
33
+ def self.encode(prefix, uuid)
34
+ [
35
+ prefix.to_s,
36
+ Base62.encode(uuid.delete("-").hex),
37
+ ].join("_")
38
+ end
39
+
40
+ def self.decode(eid)
41
+ prefix, base62 = eid.to_s.split("_", 2)
42
+
43
+ if prefix.nil? || base62.nil?
44
+ raise DecodeError, "Invalid EID #{eid.inspect}"
45
+ end
46
+
47
+ hex = Base62.decode(base62).to_s(16).rjust(32, "0")
48
+
49
+ Result.new(
50
+ prefix,
51
+ [hex[0..7], hex[8..11], hex[12..15], hex[16..19], hex[20..31]].join("-"),
52
+ )
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,119 @@
1
+ module Exid
2
+ class Record < Module
3
+ MUTEX = Mutex.new
4
+
5
+ Entry =
6
+ Data.define(:prefix, :field, :klass) do
7
+ def ==(other) = prefix == other.prefix
8
+ def hash = prefix.hash
9
+
10
+ alias_method :eql?, :==
11
+ end
12
+
13
+ @registered_modules = Set.new
14
+
15
+ def included(base)
16
+ base.send(:include, @module_value)
17
+ base.send(:include, @module_shared)
18
+ base.send(:extend, @module_shared)
19
+ base.send(:extend, @module_static)
20
+
21
+ self.class.register_module(
22
+ Entry.new(
23
+ prefix: base.prefix_eid_prefix_name,
24
+ field: base.prefix_eid_field,
25
+ klass: base,
26
+ ),
27
+ )
28
+ end
29
+
30
+ def initialize(prefix, field)
31
+ raise Error, "Prefix cannot be longer than 4 characters" if prefix.length > 4
32
+
33
+ @module_static = build_module_static(prefix, field)
34
+ @module_value = build_module_value(prefix, field)
35
+ @module_shared = build_module_shared(prefix, field)
36
+
37
+ super()
38
+ end
39
+
40
+ # When app is eager loaded in production, all models are loaded and
41
+ # registered. This logic with delte and readd is for development purpose,
42
+ # to make sure we can make changes to the app and have this logic working
43
+ # at the same time. We only use prefix as identify for the set elements.
44
+
45
+ def self.register_module(entry)
46
+ MUTEX.synchronize do
47
+ @registered_modules.delete(entry)
48
+ @registered_modules.add(entry)
49
+ end
50
+ end
51
+
52
+ def self.unload
53
+ MUTEX.synchronize do
54
+ @registered_modules = Set.new
55
+ end
56
+ end
57
+
58
+ def self.registered_modules
59
+ MUTEX.synchronize do
60
+ @registered_modules.dup
61
+ end
62
+ end
63
+
64
+ def self.find_module(prefix)
65
+ registered_modules.detect { it.prefix == prefix } or
66
+ raise Error, "Model for \"#{prefix}\" not found"
67
+ end
68
+
69
+ def self.finder(eid)
70
+ Coder.decode(eid) => prefix, value
71
+
72
+ mod = find_module(prefix)
73
+ mod.klass.where(mod.field => value)
74
+ end
75
+
76
+ def self.fetch(eid) = finder(eid).first
77
+ def self.fetch!(eid) = finder(eid).sole
78
+
79
+ private
80
+
81
+ def build_module_value(prefix, field)
82
+ Module.new do
83
+ define_method :prefix_eid_value do
84
+ Coder.encode(prefix, send(field))
85
+ end
86
+
87
+ # This is used to visually distingquish records on index pages. First
88
+ # bits of UUID7 are date, so they are shared among many records. Using
89
+ # last bytes of encoded of UUID7 is more likely to be unique. This for
90
+ # display only, do not use this to fetch records, etc.
91
+
92
+ define_method :prefix_eid_handle do |amount = 10|
93
+ prefix_eid_value.split("_").last[-amount..-1]
94
+ end
95
+ end
96
+ end
97
+
98
+ def build_module_shared(prefix, field)
99
+ Module.new do
100
+ define_method :prefix_eid_prefix_name do
101
+ prefix
102
+ end
103
+
104
+ define_method :prefix_eid_field do
105
+ field
106
+ end
107
+ end
108
+ end
109
+
110
+ def build_module_static(prefix, field)
111
+ Module.new do
112
+ define_method :prefix_eid_loader do |eid|
113
+ Coder.decode(eid) => ^prefix, value
114
+ find_sole_by(field => value)
115
+ end
116
+ end
117
+ end
118
+ end
119
+ end
data/lib/exid/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Exid
4
- VERSION = "0.1.0"
4
+ VERSION = "0.1.1"
5
5
  end
data/lib/exid.rb CHANGED
@@ -5,3 +5,10 @@ require_relative "exid/version"
5
5
  module Exid
6
6
  class Error < StandardError; end
7
7
  end
8
+
9
+ require "forwardable"
10
+ require "zeitwerk"
11
+
12
+ loader = Zeitwerk::Loader.for_gem
13
+ loader.setup
14
+ loader.eager_load
metadata CHANGED
@@ -1,14 +1,28 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: exid
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - John Doe
8
8
  bindir: exe
9
9
  cert_chain: []
10
- date: 2025-04-04 00:00:00.000000000 Z
11
- dependencies: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: zeitwerk
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '2.6'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '2.6'
12
26
  description: This is a gem for managing external identifiers in Ruby programs.
13
27
  email:
14
28
  - test@example.com
@@ -17,11 +31,13 @@ extensions: []
17
31
  extra_rdoc_files: []
18
32
  files:
19
33
  - ".rspec"
20
- - CODE_OF_CONDUCT.md
21
34
  - LICENSE.txt
22
35
  - README.md
23
36
  - Rakefile
24
37
  - lib/exid.rb
38
+ - lib/exid/base62.rb
39
+ - lib/exid/coder.rb
40
+ - lib/exid/record.rb
25
41
  - lib/exid/version.rb
26
42
  - sig/exid.rbs
27
43
  homepage: https://github.com/marzdrel/exid
@@ -43,7 +59,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
43
59
  - !ruby/object:Gem::Version
44
60
  version: '0'
45
61
  requirements: []
46
- rubygems_version: 3.6.2
62
+ rubygems_version: 3.6.7
47
63
  specification_version: 4
48
64
  summary: Easy External identifier management for models
49
65
  test_files: []
data/CODE_OF_CONDUCT.md DELETED
@@ -1,132 +0,0 @@
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