activerecord-ksuid 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 6038503571420197cb5b5c7f8cecbc1f6b358a07cc83186266f55df362115109
4
+ data.tar.gz: 29f103117d1a6cf608db290998edb04f86c493d48832483215af57ea83bf9817
5
+ SHA512:
6
+ metadata.gz: ba30a46e24e3e4faee905adcab9d94166b9a432908c30ffab5094dc76c8deea4a7744b6bb17a6eca13626d3571332eb9882536af9b01ffab43a47d78d1baf3cf
7
+ data.tar.gz: 01f5fbd805569c80ab1c42c5d5b242173b3210f26305e82042e1286a28852b9205864f0f77a87ec4da64369d1b01f02b2a932e1661f07266f79394f583b37ee9
data/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [1.0.0](https://github.com/michaelherold/ksuid/compare/v0.5.0...v1.0.0) - 2023-02-25
8
+
9
+ ### Added
10
+
11
+ - Extracted the ActiveRecord behavior from [`ksuid-v0.5.0`](https://github.com/michaelherold/ksuid-ruby/tree/v0.5.0) into its own gem to slim down the gem and remove unnecessary functionality for people who only want the KSUID functionality.
12
+ - Added the ability to disable the automatic generation of KSUIDs for fields by passing `auto_gen: false` to the module builder. This is helpful for foreign key fields, where an invalid value can raise errors, or for cases where you don't want to set the value until a later time.
13
+
14
+ ### Fixed
15
+
16
+ - Binary KSUIDs on PostgreSQL now correctly deserialize without any extra configuration.
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,55 @@
1
+ # Contributing
2
+
3
+ In the spirit of [free software], **everyone** is encouraged to help improve this project. Here are some ways *you* can contribute:
4
+
5
+ * Use alpha, beta, and pre-release versions.
6
+ * Report bugs.
7
+ * Suggest new features.
8
+ * Write or edit documentation.
9
+ * Write specifications.
10
+ * Write code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace).
11
+ * Refactor code.
12
+ * Fix [issues].
13
+ * Review patches.
14
+
15
+ [free software]: http://www.fsf.org/licensing/essays/free-sw.html
16
+ [issues]: https://github.com/michaelherold/ksuid-ruby/issues
17
+
18
+ ## Submitting an Issue
19
+
20
+ We use the [GitHub issue tracker][issues] to track bugs and features. Before submitting a bug report or feature request, check to make sure it hasn't already been submitted.
21
+
22
+ When submitting a bug report, please include a [Gist](https://gist.github.com) that includes a stack trace and any details that may be necessary to reproduce the bug, including your gem version, Ruby version, and operating system.
23
+
24
+ Ideally, a bug report should include a pull request with failing specs.
25
+
26
+ ## Submitting a Pull Request
27
+
28
+ 1. [Fork the repository].
29
+ 2. [Create a topic branch].
30
+ 3. Add specs for your unimplemented feature or bug fix.
31
+ 4. Run `appraisal rake spec`. If your specs pass, return to step 3.
32
+ 5. Implement your feature or bug fix.
33
+ 6. Run `appraisal rake`. If your specs or any of the linters fail, return to step 5.
34
+ 7. Open `coverage/index.html`. If your changes are not completely covered by your tests, return to step 3.
35
+ 8. Add documentation for your feature or bug fix.
36
+ 9. Commit and push your changes.
37
+ 10. [Submit a pull request].
38
+
39
+ [Create a topic branch]: https://help.github.com/articles/creating-and-deleting-branches-within-your-repository/
40
+ [Fork the repository]: http://learn.github.com/p/branching.html
41
+ [Submit a pull request]: https://help.github.com/articles/creating-a-pull-request/
42
+
43
+ ## Tools to Help You Succeed
44
+
45
+ You will need a working copy of MySQL and PostgreSQL to run tests against them. At the root level of the gem, there is a `docker-compose.yml` file that sets up both of these services for you using either [Podman Compose](https://github.com/containers/podman-compose) or [Docker Compose](https://docs.docker.com/compose/). Both of these services will bind their default ports, so keep that in mind if you already have either database running on that port. Assuming you picked Podman, run:
46
+
47
+ podman-compose up
48
+
49
+ in the `activerecord-ksuid` directory to start the services.
50
+
51
+ After checking out the repository, run `bin/setup` to install dependencies. Then, run `appraisal rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
52
+
53
+ Before committing code, run `appraisal rake` to check that the code conforms to the style guidelines of the project, that all of the tests are green (if you're writing a feature; if you're only submitting a failing test, then it does not have to pass!), and that the changes are sufficiently documented.
54
+
55
+ [rubygems]: https://rubygems.org
data/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ # The MIT License (MIT)
2
+
3
+ Copyright © 2017-2022 Michael Herold
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ 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, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,251 @@
1
+ # KSUID for ActiveRecord
2
+
3
+ [![Build Status](https://github.com/michaelherold/ksuid-ruby/workflows/CI/badge.svg)][actions]
4
+ [![Test Coverage](https://api.codeclimate.com/v1/badges/94b2a2d4082bff21c10f/test_coverage)][test-coverage]
5
+ [![Maintainability](https://api.codeclimate.com/v1/badges/94b2a2d4082bff21c10f/maintainability)][maintainability]
6
+ [![Inline docs](http://inch-ci.org/github/michaelherold/ksuid-ruby.svg?branch=main)][inch]
7
+
8
+ [actions]: https://github.com/michaelherold/ksuid-ruby/actions
9
+ [inch]: http://inch-ci.org/github/michaelherold/ksuid-ruby
10
+ [maintainability]: https://codeclimate.com/github/michaelherold/ksuid-ruby/maintainability
11
+ [test-coverage]: https://codeclimate.com/github/michaelherold/ksuid-ruby/test_coverage
12
+
13
+ activerecord-ksuid is a Ruby library that enables the use of [KSUIDs](https://github.com/segmentio/ksuid) within ActiveRecord. The original readme for the Go version of KSUID does a great job of explaining what they are and how they should be used, so it is excerpted here.
14
+
15
+ ---
16
+
17
+ # What is a KSUID?
18
+
19
+ KSUID is for K-Sortable Unique IDentifier. It's a way to generate globally unique IDs similar to RFC 4122 UUIDs, but contain a time component so they can be "roughly" sorted by time of creation. The remainder of the KSUID is randomly generated bytes.
20
+
21
+ # Why use KSUIDs?
22
+
23
+ Distributed systems often require unique IDs. There are numerous solutions out there for doing this, so why KSUID?
24
+
25
+ ## 1. Sortable by Timestamp
26
+
27
+ Unlike the more common choice of UUIDv4, KSUIDs contain a timestamp component that allows them to be roughly sorted by generation time. This is obviously not a strong guarantee as it depends on wall clocks, but is still incredibly useful in practice.
28
+
29
+ ## 2. No Coordination Required
30
+
31
+ [Snowflake IDs][1] and derivatives require coordination, which significantly increases the complexity of implementation and creates operations overhead. While RFC 4122 UUIDv1 does have a time component, there aren't enough bytes of randomness to provide strong protections against duplicate ID generation.
32
+
33
+ KSUIDs use 128-bits of pseudorandom data, which provides a 64-times larger number space than the 122-bits in the well-accepted RFC 4122 UUIDv4 standard. The additional timestamp component drives down the extremely rare chance of duplication to the point of near physical infeasibility, even assuming extreme clock skew (> 24-hours) that would cause other severe anomalies.
34
+
35
+ [1]: https://blog.twitter.com/2010/announcing-snowflake
36
+
37
+ ## 3. Lexicographically Sortable, Portable Representations
38
+
39
+ The binary and string representations are lexicographically sortable, which allows them to be dropped into systems which do not natively support KSUIDs and retain their k-sortable characteristics.
40
+
41
+ The string representation is that it is base 62-encoded, so that they can "fit" anywhere alphanumeric strings are accepted.
42
+
43
+ # How do they work?
44
+
45
+ KSUIDs are 20-bytes: a 32-bit unsigned integer UTC timestamp and a 128-bit randomly generated payload. The timestamp uses big-endian encoding, to allow lexicographic sorting. The timestamp epoch is adjusted to March 5th, 2014, providing over 100 years of useful life starting at UNIX epoch + 14e8. The payload uses a cryptographically strong pseudorandom number generator.
46
+
47
+ The string representation is fixed at 27-characters encoded using a base 62 encoding that also sorts lexicographically.
48
+
49
+ ---
50
+
51
+ ## Installation
52
+
53
+ Add this line to your application's Gemfile:
54
+
55
+ ```ruby
56
+ gem 'activerecord-ksuid', require: 'active_record/ksuid/railtie'
57
+ ```
58
+
59
+ And then execute:
60
+
61
+ $ bundle
62
+
63
+ Or install it yourself as:
64
+
65
+ $ gem install ksuid
66
+
67
+ ## Usage
68
+
69
+ Whether you are using ActiveRecord inside an existing project or in a new project, usage is simple. Additionally, you can use it with or without Rails.
70
+
71
+ #### Adding to an existing model
72
+
73
+ Within a Rails project, it is easy to get started using KSUIDs within your models. You can use the `ksuid` column type in a Rails migration to add a column to an existing model:
74
+
75
+ rails generate migration add_ksuid_to_events unique_id:ksuid
76
+
77
+ This will generate a migration like the following:
78
+
79
+ ```ruby
80
+ class AddKsuidToEvents < ActiveRecord::Migration[5.2]
81
+ def change
82
+ add_column :events, :unique_id, :ksuid
83
+ end
84
+ end
85
+ ```
86
+
87
+ Then, to add proper handling to the field, you will want to mix a module into the model:
88
+
89
+ ```ruby
90
+ class Event < ApplicationRecord
91
+ include ActiveRecord::KSUID[:unique_id]
92
+ end
93
+ ```
94
+
95
+ #### Creating a new model
96
+
97
+ To create a new model with a `ksuid` field that serializes as a KSUID string, use the `ksuid` column type. Using the Rails generators, this looks like:
98
+
99
+ rails generate model Event my_field_name:ksuid
100
+
101
+ If you would like to add a KSUID to an existing model, you can do so with the following:
102
+
103
+ ```ruby
104
+ class AddKsuidToEvents < ActiveRecord::Migration[5.2]
105
+ change_table :events do |table|
106
+ table.ksuid :my_field_name
107
+ end
108
+ end
109
+ ```
110
+
111
+ Once you have generated the table that you will use for your model, you will need to include a module into the model class, as follows:
112
+
113
+ ```ruby
114
+ class Event < ApplicationRecord
115
+ include ActiveRecord::KSUID[:my_field_name]
116
+ end
117
+ ```
118
+
119
+ ##### With a KSUID primary key
120
+
121
+ You can also use a KSUID as the primary key on a table, much like you can use a UUID in vanilla Rails. To do so requires a little more finagling than you can manage through the generators. When hand-writing the migration, it will look like this:
122
+
123
+ ```ruby
124
+ class CreateEvents < ActiveRecord::Migration[5.2]
125
+ create_table :events, id: false do |table|
126
+ table.ksuid :id, primary_key: true
127
+ end
128
+ end
129
+ ```
130
+
131
+ You will need to mix in the module into your model as well:
132
+
133
+ ```ruby
134
+ class Event < ApplicationRecord
135
+ include ActiveRecord::KSUID[:id]
136
+ end
137
+ ```
138
+
139
+ ##### Without generating a default value
140
+
141
+ In some cases, such as foreign keys, you do not want to generate a default value for the field and, instead, want to set the value manually. When this is true, you can disable the default generation behavior by passing `auto_gen: false` to the module builder.
142
+
143
+ ```ruby
144
+ class Event < ApplicationRecord
145
+ include ActiveRecord::KSUID[:correlation_id, auto_gen: false]
146
+
147
+ belongs_to :correlation, class_name: Event
148
+ end
149
+ ```
150
+
151
+ You can also use the [Attributes API](http://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html) directly:
152
+
153
+ ```ruby
154
+ class Event < ApplicationRecord
155
+ attribute :correlation_id, :ksuid
156
+
157
+ belongs_to :correlation, class_name: Event
158
+ end
159
+ ```
160
+
161
+ #### Outside of Rails
162
+
163
+ Outside of Rails, you cannot rely on the Railtie to load the appropriate files for you automatically. Toward the start of your application's boot process, you will want to require the following:
164
+
165
+ ```ruby
166
+ require 'ksuid'
167
+ require 'active_record/ksuid'
168
+
169
+ # If you will be using the ksuid column type in a migration
170
+ require 'active_record/ksuid/table_definition'
171
+ ```
172
+
173
+ Once you have required the file(s) that you need, everything else will work as it does above.
174
+
175
+ #### Binary vs. String KSUIDs
176
+
177
+ These examples all store your identifier as a string-based KSUID. If you would like to use binary KSUIDs instead, use the `ksuid_binary` column type. Unless you need to be super-efficient with your database, we recommend using string-based KSUIDs because it makes looking at the data while in the database a little easier to understand.
178
+
179
+ When you include the KSUID module into your model, you will want to pass the `:binary` option as well:
180
+
181
+ ```ruby
182
+ class Event < ApplicationRecord
183
+ include ActiveRecord::KSUID[:my_field_name, binary: true]
184
+ end
185
+ ```
186
+
187
+ #### Using a prefix on your KSUID field
188
+
189
+ For prefixed KSUIDs in ActiveRecord, you must pass the intended prefix during table definition so that the field is of appropriate size.
190
+
191
+ ```ruby
192
+ class CreateEvents < ActiveRecord::Migration[5.2]
193
+ create_table :events do |table|
194
+ table.ksuid :ksuid, prefix: 'evt_'
195
+ end
196
+ end
197
+ ```
198
+
199
+ You also must pass it in the module builder that you include in your model:
200
+
201
+ ```ruby
202
+ class Event < ApplicationRecord
203
+ include ActiveRecord::KSUID[:ksuid, prefix: 'evt_']
204
+ end
205
+ ```
206
+
207
+ You cannot use a prefix with a binary-encoded KSUID.
208
+
209
+ #### Use the KSUID as your `created_at` timestamp
210
+
211
+ Since KSUIDs include a timestamp as well, you can infer the `#created_at` timestamp from the KSUID. The module builder enables that option automatically with the `:created_at` option, like so:
212
+
213
+ ```ruby
214
+ class Event < ApplicationRecord
215
+ include ActiveRecord::KSUID[:my_field_name, created_at: true]
216
+ end
217
+ ```
218
+
219
+ This allows you to be efficient in your database design if that is a constraint you need to satisfy.
220
+
221
+ ## Contributing
222
+
223
+ So you’re interested in contributing to KSUID for ActiveRecord? Check out our [contributing guidelines](CONTRIBUTING.md) for more information on how to do that.
224
+
225
+ ## Supported Ruby Versions
226
+
227
+ This library aims to support and is [tested against][actions] the following Ruby versions:
228
+
229
+ * Ruby 2.7
230
+ * Ruby 3.0
231
+ * Ruby 3.1
232
+ * JRuby 9.3
233
+
234
+ If something doesn't work on one of these versions, it's a bug.
235
+
236
+ This library may inadvertently work (or seem to work) on other Ruby versions, however support will only be provided for the versions listed above.
237
+
238
+ If you would like this library to support another Ruby version or implementation, you may volunteer to be a maintainer. Being a maintainer entails making sure all tests run and pass on that implementation. When something breaks on your implementation, you will be responsible for providing patches in a timely fashion. If critical issues for a particular implementation exist at the time of a major release, support for that Ruby version may be dropped.
239
+
240
+ ## Versioning
241
+
242
+ This library aims to adhere to [Semantic Versioning 2.0.0][semver]. Violations of this scheme should be reported as bugs. Specifically, if a minor or patch version is released that breaks backward compatibility, that version should be immediately yanked and/or a new version should be immediately released that restores compatibility. Breaking changes to the public API will only be introduced with new major versions. As a result of this policy, you can (and should) specify a dependency on this gem using the [Pessimistic Version Constraint][pessimistic] with two digits of precision. For example:
243
+
244
+ spec.add_dependency "activerecord-ksuid", "~> 1.0"
245
+
246
+ [pessimistic]: http://guides.rubygems.org/patterns/#pessimistic-version-constraint
247
+ [semver]: http://semver.org/spec/v2.0.0.html
248
+
249
+ ## License
250
+
251
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/UPGRADING.md ADDED
@@ -0,0 +1,18 @@
1
+ # Upgrading instructions for KSUID for ActiveRecord
2
+
3
+ ## v1.0.0
4
+
5
+ This is the initial release of this library. If you are upgrading from KSUID for Ruby 0.x, follow the notice below.
6
+
7
+ ### Extracted `ActiveRecord::KSUID` into its own gem
8
+
9
+ That KSUID for Ruby included ActiveRecord support directly in its gem has always been a regret of mine. It adds ActiveRecord and Rails concerns to a gem that you can use in any context. It makes running the test suite more complicated for no real gain. And it makes it kludgy to add support for more systems, like Sequel, since you have conflicting concerns in the same gem.
10
+
11
+ To remove this problem, v1.0.0 extracts the ActiveRecord behavior into its own gem, `activerecord-ksuid`. This version is a straight extraction with an improved test suite so it _should_ mean that the only change you have to make when upgrading from v0.5.0 is to do the following in your Gemfile:
12
+
13
+ ```diff
14
+ - gem 'ksuid'
15
+ + gem 'activerecord-ksuid'
16
+ ```
17
+
18
+ If you are still on a version of KSUID for Ruby prior to v0.5.0, upgrade to that version first, solve the deprecation notice below, ensure your app still works, and then upgrade to v1.0.0.
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require File.expand_path(File.join(__dir__, 'lib', 'active_record', 'ksuid', 'version'))
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'activerecord-ksuid'
7
+ spec.version = ActiveRecord::KSUID::VERSION
8
+ spec.authors = ['Michael Herold']
9
+ spec.email = ['opensource@michaeljherold.com']
10
+
11
+ spec.summary = 'ActiveRecord integration for KSUIDs using the ksuid gem'
12
+ spec.description = spec.summary
13
+ spec.homepage = 'https://github.com/michaelherold/ksuid-ruby'
14
+ spec.license = 'MIT'
15
+
16
+ spec.files = %w[CHANGELOG.md CONTRIBUTING.md LICENSE.md README.md UPGRADING.md]
17
+ spec.files += %w[activerecord-ksuid.gemspec]
18
+ spec.files += Dir['lib/**/*.rb']
19
+ spec.require_paths = ['lib']
20
+
21
+ spec.metadata['rubygems_mfa_required'] = 'true'
22
+
23
+ spec.add_dependency 'activerecord', '>= 6.0'
24
+ spec.add_dependency 'ksuid', '~> 1.0'
25
+
26
+ spec.add_development_dependency 'bundler', '>= 1.15'
27
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module KSUID
5
+ # A binary-serialized KSUID for storage within an ActiveRecord database
6
+ #
7
+ # @api private
8
+ #
9
+ # @example Set an attribute as a KSUID using the verbose syntax
10
+ # class EventWithBareBinaryType < ActiveRecord::Base
11
+ # attribute :ksuid, ActiveRecord::KSUID::BinaryType.new, default: -> { KSUID.new }
12
+ # end
13
+ #
14
+ # @example Set an attribute as a KSUID using the pre-registered type
15
+ # class EventWithRegisteredBinaryType < ActiveRecord::Base
16
+ # attribute :ksuid, :ksuid_binary, default: -> { KSUID.new }
17
+ # end
18
+ class BinaryType < ::ActiveRecord::Type::Binary
19
+ # Casts a value from user input into a KSUID
20
+ #
21
+ # Type casting happens via the attribute setter and can take input from
22
+ # many places, including:
23
+ #
24
+ # 1. The Rails form builder
25
+ # 2. Directly from the attribute setter
26
+ # 3. From the model initializer
27
+ #
28
+ # @param value [String, Array<Integer>, KSUID::Type] the value to cast into a KSUID
29
+ # @return [KSUID::Type] the type-casted value
30
+ def cast(value)
31
+ ::KSUID.call(value)
32
+ end
33
+
34
+ # Converts a value from database input to a KSUID
35
+ #
36
+ # @param value [String, nil] the database-serialized KSUID to convert
37
+ # @return [KSUID::Type] the deserialized KSUID
38
+ def deserialize(value)
39
+ return unless value
40
+
41
+ value = value.to_s if value.is_a?(::ActiveRecord::Type::Binary::Data)
42
+ value = ::KSUID::Utils.byte_string_from_hex(value[2..]) if value.start_with?('\x')
43
+ ::KSUID.call(value)
44
+ end
45
+
46
+ # Casts the value from a KSUID into a database-understandable format
47
+ #
48
+ # @param value [KSUID::Type, nil] the KSUID in Ruby format
49
+ # @return [String, nil] the base 62-encoded KSUID for storage in the database
50
+ def serialize(value)
51
+ return unless value
52
+
53
+ super(::KSUID.call(value).to_bytes)
54
+ end
55
+ end
56
+ end
57
+ end
58
+
59
+ ActiveRecord::Type.register(:ksuid_binary, ActiveRecord::KSUID::BinaryType)
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module KSUID
5
+ # A string-serialized, prefixed KSUID for storage within an ActiveRecord database
6
+ #
7
+ # @api private
8
+ # @since 0.5.0
9
+ #
10
+ # @example Set an attribute as a prefixed KSUID using the verbose syntax
11
+ # class EventWithBarePrefixedType < ActiveRecord::Base
12
+ # attribute(
13
+ # :ksuid,
14
+ # ActiveRecord::KSUID::PrefixedType.new(prefix: 'evt_'),
15
+ # default: -> { KSUID.prefixed('evt_') }
16
+ # )
17
+ # end
18
+ #
19
+ # @example Set an attribute as a prefixed KSUID using the pre-registered type
20
+ # class EventWithRegisteredPrefixedType < ActiveRecord::Base
21
+ # attribute :ksuid, :ksuid_prefixed, prefix: 'evt_', default: -> { KSUID.prefixed('evt_') }
22
+ # end
23
+ class PrefixedType < ::ActiveRecord::Type::String
24
+ # Instantiates an ActiveRecord::Type for handling prefixed KSUIDs
25
+ #
26
+ # @param prefix [String] the prefix to add to the KSUID
27
+ def initialize(prefix: '')
28
+ @prefix = prefix
29
+ super()
30
+ end
31
+
32
+ # Casts a value from user input into a {KSUID::Prefixed}
33
+ #
34
+ # Type casting happens via the attribute setter and can take input from
35
+ # many places, including:
36
+ #
37
+ # 1. The Rails form builder
38
+ # 2. Directly from the attribute setter
39
+ # 3. From the model initializer
40
+ #
41
+ # @param value [String, Array<Integer>, KSUID::Prefixed] the value to cast into a KSUID
42
+ # @return [KSUID::Prefixed] the type-casted value
43
+ def cast(value)
44
+ ::KSUID::Prefixed.call(value, prefix: @prefix)
45
+ end
46
+
47
+ # Converts a value from database input to a {KSUID::Prefixed}
48
+ #
49
+ # @param value [String, nil] the database-serialized, prefixed KSUID to convert
50
+ # @return [KSUID::Prefixed] the deserialized, prefixed KSUID
51
+ def deserialize(value)
52
+ return unless value
53
+
54
+ ::KSUID::Prefixed.from_base62(value, prefix: @prefix)
55
+ end
56
+
57
+ # Casts the value from a KSUID into a database-understandable format
58
+ #
59
+ # @param value [KSUID::Prefixed, nil] the prefixed KSUID in Ruby format
60
+ # @return [String, nil] the base 62-encoded, prefixed KSUID for storage in the database
61
+ def serialize(value)
62
+ return unless value
63
+
64
+ ::KSUID::Prefixed.call(value, prefix: @prefix).to_s
65
+ end
66
+ end
67
+ end
68
+ end
69
+
70
+ ActiveRecord::Type.register(:ksuid_prefixed, ActiveRecord::KSUID::PrefixedType)
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module KSUID
5
+ # Enables the usage of KSUID types within ActiveRecord when Rails is loaded
6
+ #
7
+ # @api private
8
+ class Railtie < ::Rails::Railtie
9
+ initializer 'ksuid' do
10
+ require 'ksuid'
11
+
12
+ ActiveSupport.on_load :active_record do
13
+ require 'active_record/ksuid'
14
+ end
15
+ end
16
+
17
+ initializer 'ksuid.table_definition' do
18
+ ActiveSupport.on_load :active_record do
19
+ require 'active_record/ksuid/table_definition'
20
+
21
+ ActiveRecord::ConnectionAdapters::TableDefinition.include(
22
+ ActiveRecord::KSUID::TableDefinition
23
+ )
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module KSUID
5
+ # Extends ActiveRecord's table definition language for KSUIDs
6
+ module TableDefinition
7
+ # Defines a field as a string-based KSUID
8
+ #
9
+ # @example Define a KSUID field as a non-primary key
10
+ # ActiveRecord::Schema.define do
11
+ # create_table :events, force: true do |table|
12
+ # table.ksuid :ksuid, index: true, unique: true
13
+ # end
14
+ # end
15
+ #
16
+ # @example Define a KSUID field as a primary key
17
+ # ActiveRecord::Schema.define do
18
+ # create_table :events, force: true, id: false do |table|
19
+ # table.ksuid :id, primary_key: true
20
+ # end
21
+ # end
22
+ #
23
+ # @param args [Array<Symbol>] the list of fields to define as KSUIDs
24
+ # @param options [Hash] see {ActiveRecord::ConnectionAdapters::TableDefinition}
25
+ # @option options [String] :prefix the prefix expected in front of the KSUID
26
+ # @return [void]
27
+ def ksuid(*args, **options)
28
+ prefix_length = options.delete(:prefix)&.length || 0
29
+
30
+ args.each { |name| column(name, :string, **options.merge(limit: 27 + prefix_length)) }
31
+ end
32
+
33
+ # Defines a field as a binary-based KSUID
34
+ #
35
+ # @example Define a KSUID field as a non-primary key
36
+ # ActiveRecord::Schema.define do
37
+ # create_table :events, force: true do |table|
38
+ # table.ksuid_binary :ksuid, index: true, unique: true
39
+ # end
40
+ # end
41
+ #
42
+ # @example Define a KSUID field as a primary key
43
+ # ActiveRecord::Schema.define do
44
+ # create_table :events, force: true, id: false do |table|
45
+ # table.ksuid_binary :id, primary_key: true
46
+ # end
47
+ # end
48
+ #
49
+ # @param args [Array<Symbol>] the list of fields to define as KSUIDs
50
+ # @param options [Hash] see {ActiveRecord::ConnectionAdapters::TableDefinition}
51
+ # @return [void]
52
+ def ksuid_binary(*args, **options)
53
+ args.each { |name| column(name, :binary, **options.merge(limit: 20)) }
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module KSUID
5
+ # A string-serialized KSUID for storage within an ActiveRecord database
6
+ #
7
+ # @api private
8
+ #
9
+ # @example Set an attribute as a KSUID using the verbose syntax
10
+ # class EventWithBareType < ActiveRecord::Base
11
+ # attribute :ksuid, ActiveRecord::KSUID::Type.new, default: -> { KSUID.new }
12
+ # end
13
+ #
14
+ # @example Set an attribute as a KSUID using the pre-registered type
15
+ # class EventWithRegisteredType < ActiveRecord::Base
16
+ # attribute :ksuid, :ksuid, default: -> { KSUID.new }
17
+ # end
18
+ class Type < ::ActiveRecord::Type::String
19
+ # Casts a value from user input into a KSUID
20
+ #
21
+ # Type casting happens via the attribute setter and can take input from
22
+ # many places, including:
23
+ #
24
+ # 1. The Rails form builder
25
+ # 2. Directly from the attribute setter
26
+ # 3. From the model initializer
27
+ #
28
+ # @param value [String, Array<Integer>, KSUID::Type] the value to cast into a KSUID
29
+ # @return [KSUID::Type] the type-casted value
30
+ def cast(value)
31
+ ::KSUID.call(value)
32
+ end
33
+
34
+ # Converts a value from database input to a KSUID
35
+ #
36
+ # @param value [String, nil] the database-serialized KSUID to convert
37
+ # @return [KSUID::Type] the deserialized KSUID
38
+ def deserialize(value)
39
+ return unless value
40
+
41
+ ::KSUID.from_base62(value)
42
+ end
43
+
44
+ # Casts the value from a KSUID into a database-understandable format
45
+ #
46
+ # @param value [KSUID::Type, nil] the KSUID in Ruby format
47
+ # @return [String, nil] the base 62-encoded KSUID for storage in the database
48
+ def serialize(value)
49
+ return unless value
50
+
51
+ ::KSUID.call(value).to_s
52
+ end
53
+ end
54
+ end
55
+ end
56
+
57
+ ActiveRecord::Type.register(:ksuid, ActiveRecord::KSUID::Type)
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module KSUID
5
+ # The version of the activerecord-ksuid gem
6
+ #
7
+ # @return [String]
8
+ VERSION = '1.0.0'
9
+ end
10
+ end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record/ksuid/binary_type'
4
+ require 'active_record/ksuid/prefixed_type'
5
+ require 'active_record/ksuid/type'
6
+
7
+ # The Ruby on Rails object-relational mapper
8
+ #
9
+ # @see https://guides.rubyonrails.org/ Ruby on Rails documentation
10
+ module ActiveRecord
11
+ # Enables an Active Record model to have a KSUID attribute
12
+ #
13
+ # @api public
14
+ # @since 0.5.0
15
+ module KSUID
16
+ # Builds a module to include into the model
17
+ #
18
+ # @api public
19
+ #
20
+ # @example Add a `#ksuid` attribute to a model
21
+ # class Event < ActiveRecord::Base
22
+ # include ActiveRecord::KSUID[:ksuid]
23
+ # end
24
+ #
25
+ # @example Add a `#remote_id` attribute to a model and overrides `#created_at` to use the KSUID
26
+ # class Event < ActiveRecord::Base
27
+ # include ActiveRecord::KSUID[:remote_id, created_at: true]
28
+ # end
29
+ #
30
+ # @example Add a prefixed `#ksuid` attribute to a model
31
+ # class Event < ActiveRecord::Base
32
+ # include ActiveRecord::KSUID[:ksuid, prefix: 'evt_']
33
+ # end
34
+ #
35
+ # @param auto_gen [Boolean] whether to generate a KSUID upon initialization
36
+ # @param field [String, Symbol] the name of the field to use as a KSUID
37
+ # @param created_at [Boolean] whether to override the `#created_at` method
38
+ # @param binary [Boolean] whether to store the KSUID as a binary or a string
39
+ # @param prefix [String, nil] a prefix to prepend to the KSUID attribute
40
+ # @return [Module] the module to include into the model
41
+ def self.[](field, auto_gen: true, created_at: false, binary: false, prefix: nil)
42
+ raise ArgumentError, 'cannot include a prefix on a binary KSUID' if binary && prefix
43
+
44
+ Module.new.tap do |mod|
45
+ if prefix
46
+ define_prefixed_attribute(field, mod, auto_gen, prefix)
47
+ else
48
+ define_attribute(field, mod, auto_gen, binary)
49
+ end
50
+ define_created_at(field, mod) if created_at
51
+ end
52
+ end
53
+
54
+ # Defines the attribute method that will be written in the module
55
+ #
56
+ # @api private
57
+ #
58
+ # @param field [String, Symbol] the name of the field to set as an attribute
59
+ # @param mod [Module] the module to extend
60
+ # @param auto_gen [Boolean] whether to generate a KSUID upon initialization
61
+ # @param binary [Boolean] whether to store the KSUID as a binary or a string
62
+ # @return [void]
63
+ def self.define_attribute(field, mod, auto_gen, binary)
64
+ type = 'ksuid'
65
+ type = 'ksuid_binary' if binary
66
+ default = 'default: -> { ::KSUID.new }' if auto_gen
67
+
68
+ mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
69
+ def self.included(base) # def self.included(base)
70
+ base.__send__( # base.__send__(
71
+ :attribute, # :attribute,
72
+ :#{field}, # :id,
73
+ :#{type}, # :ksuid,
74
+ #{default} # default: -> { ::KSUID.new }
75
+ ) # )
76
+ end # end
77
+ RUBY
78
+ end
79
+ private_class_method :define_attribute
80
+
81
+ # Defines the attribute method that will be written in the module for a field
82
+ #
83
+ # @api private
84
+ #
85
+ # @param field [String, Symbol] the name of the field to set as an attribute
86
+ # @param mod [Module] the module to extend
87
+ # @param auto_gen [Boolean] whether to generate a KSUID upon initialization
88
+ # @param prefix [String] the prefix to add to the KSUID
89
+ # @return [void]
90
+ def self.define_prefixed_attribute(field, mod, auto_gen, prefix)
91
+ default = "default: -> { ::KSUID.prefixed('#{prefix}') }" if auto_gen
92
+
93
+ mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
94
+ def self.included(base) # def self.included(base)
95
+ base.__send__( # base.__send__(
96
+ :attribute, # :attribute,
97
+ :#{field}, # :id,
98
+ :ksuid_prefixed, # :ksuid_prefixed,
99
+ prefix: #{prefix.inspect}, # prefix: 'evt_'
100
+ #{default} # default: -> { ::KSUID.prefixed('evt_') }
101
+ ) # )
102
+ end # end
103
+ RUBY
104
+ end
105
+ private_class_method :define_prefixed_attribute
106
+
107
+ # Defines the `#created_at` method that will be written in the module
108
+ #
109
+ # @api private
110
+ #
111
+ # @param field [String, Symbol] the name of the KSUID attribute field
112
+ # @param mod [Module] the module to extend
113
+ # @return [void]
114
+ def self.define_created_at(field, mod)
115
+ mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
116
+ def created_at # def created_at
117
+ return unless #{field} # return unless ksuid
118
+
119
+ #{field}.to_time # ksuid.to_time
120
+ end # end
121
+ RUBY
122
+ end
123
+ private_class_method :define_created_at
124
+ end
125
+ end
126
+
127
+ require 'active_record/ksuid/railtie' if defined?(Rails)
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record/ksuid'
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: activerecord-ksuid
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Michael Herold
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2023-02-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: ksuid
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '1.15'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '1.15'
55
+ description: ActiveRecord integration for KSUIDs using the ksuid gem
56
+ email:
57
+ - opensource@michaeljherold.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - CHANGELOG.md
63
+ - CONTRIBUTING.md
64
+ - LICENSE.md
65
+ - README.md
66
+ - UPGRADING.md
67
+ - activerecord-ksuid.gemspec
68
+ - lib/active_record/ksuid.rb
69
+ - lib/active_record/ksuid/binary_type.rb
70
+ - lib/active_record/ksuid/prefixed_type.rb
71
+ - lib/active_record/ksuid/railtie.rb
72
+ - lib/active_record/ksuid/table_definition.rb
73
+ - lib/active_record/ksuid/type.rb
74
+ - lib/active_record/ksuid/version.rb
75
+ - lib/activerecord-ksuid.rb
76
+ homepage: https://github.com/michaelherold/ksuid-ruby
77
+ licenses:
78
+ - MIT
79
+ metadata:
80
+ rubygems_mfa_required: 'true'
81
+ post_install_message:
82
+ rdoc_options: []
83
+ require_paths:
84
+ - lib
85
+ required_ruby_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ required_rubygems_version: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: '0'
95
+ requirements: []
96
+ rubygems_version: 3.3.7
97
+ signing_key:
98
+ specification_version: 4
99
+ summary: ActiveRecord integration for KSUIDs using the ksuid gem
100
+ test_files: []