append_transitions 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: '09ccaf36ce8a024a0df600276c365a8354c6fc4bde2f991d3c1fd780086303c0'
4
+ data.tar.gz: d3834ef30799b12effb012daa09cceee4da9820ae71f9273b94fb11af97be8df
5
+ SHA512:
6
+ metadata.gz: be72964c6626684f49e076cf1f9924331fc8375865b5c9395399505b28a27c01e5df10ede68bfbe4880875bddcc5455732c7c5084f1578591bac6d02d236ffa7
7
+ data.tar.gz: 52f12083f9f5b888462fc2cb2ea1f61c1c7218b57e8dc0dba16b63cecbfd82b2c9eb0e1e42cb69203b56d73eaf1b89d149cd23cfc654aa17fe0681eb5745e583
data/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file. The
4
+ format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-11-27
10
+
11
+ Initial release.
12
+
13
+ ### Added
14
+
15
+ - `AppendTransitions::HasCurrent`, which adds `current_*`,
16
+ `transition_*` and `with_current_*` to a model whose state lives in
17
+ an append-only table.
18
+ - Transitions validated against an initial state and allowed
19
+ transitions, and serialized with a row lock on the parent.
20
+ - `with_current_*`, which loads each record's current state in the
21
+ same query through a `LEFT JOIN LATERAL`.
22
+ - A check for the index lookups read through, configurable to warn or
23
+ raise.
24
+ - The `append_transitions:state` generator, which creates the state
25
+ table, its index and a read-only model.
26
+
27
+ [Unreleased]: https://github.com/thoughtbot/append_transitions/compare/v0.1.0...HEAD
28
+ [0.1.0]: https://github.com/thoughtbot/append_transitions/releases/tag/v0.1.0
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,70 @@
1
+ # Contributing
2
+
3
+ [Bug reports][bugs] and [pull requests][prs] are welcome on GitHub
4
+ at https://github.com/thoughtbot/append_transitions.
5
+
6
+ [bugs]: https://github.com/thoughtbot/append_transitions/issues/new
7
+ [prs]: https://github.com/thoughtbot/append_transitions/pulls
8
+
9
+ Please create a [new discussion][discussion] if you want to share
10
+ ideas for new features.
11
+
12
+ [discussion]: https://github.com/thoughtbot/append_transitions/discussions/new?category=ideas
13
+
14
+ We love contributions from everyone.
15
+ By participating in this project,
16
+ you agree to abide by the thoughtbot [code of conduct].
17
+
18
+ [code of conduct]: https://thoughtbot.com/open-source-code-of-conduct
19
+
20
+ We expect everyone to follow the code of conduct
21
+ anywhere in thoughtbot's project codebases,
22
+ issue trackers, chatrooms, and mailing lists.
23
+
24
+ ## Contributing Code
25
+
26
+ Fork the repo.
27
+
28
+ Run the setup script.
29
+
30
+ ```
31
+ ./bin/setup
32
+ ```
33
+
34
+ The tests need a local PostgreSQL database named
35
+ `append_transitions_test`:
36
+
37
+ ```
38
+ createdb append_transitions_test
39
+ ```
40
+
41
+ Make sure everything passes:
42
+
43
+ ```
44
+ bundle exec rake
45
+ ```
46
+
47
+ Make your change, with new passing tests. Before pushing, run
48
+ `bundle exec rake` again to make sure nothing is broken.
49
+
50
+ Push to your fork. Write a [good commit message][commit]. Submit a
51
+ pull request.
52
+
53
+ [commit]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
54
+
55
+ Others will give constructive feedback.
56
+ This is a time for discussion and improvements,
57
+ and making the necessary changes will be required before we can
58
+ merge the contribution.
59
+
60
+ ## Publishing to RubyGems
61
+
62
+ When the gem is ready to be shared as a formal release, it can be
63
+ [published][published] to RubyGems.
64
+
65
+ [published]: https://guides.rubyonrails.org/plugins.html#publishing-your-gem
66
+
67
+ 1. Bump the version number in `AppendTransitions::VERSION`
68
+ 2. Run `bundle exec rake build`
69
+ 3. Run `bundle exec rake install`
70
+ 4. Run `bundle exec rake release`
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) thoughtbot, inc.
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,467 @@
1
+ # AppendTransitions
2
+
3
+ [![CI](https://github.com/thoughtbot/append_transitions/actions/workflows/ci.yml/badge.svg)](https://github.com/thoughtbot/append_transitions/actions/workflows/ci.yml)
4
+
5
+ AppendTransitions implements a better default for state transitions
6
+ in ActiveRecord: each transition is a new row, and PostgreSQL does the
7
+ work of keeping that efficient.
8
+
9
+ ## Why AppendTransitions?
10
+
11
+ AppendTransitions packages a practice: store each state transition
12
+ as its own row instead of overwriting a column.
13
+
14
+ Most applications track state with a mutable string column:
15
+
16
+ ```
17
+ users
18
+ id
19
+ status
20
+ ```
21
+
22
+ That works until someone asks when a user was approved, or how
23
+ long they waited. Each update overwrites the previous state, and you
24
+ can't backfill history you never recorded. Adding a separate history
25
+ table later doesn't fully fix it. Now the column and the history
26
+ have to be kept in sync, and they can drift apart.
27
+
28
+ With AppendTransitions, the state lives in its own table, and each
29
+ transition adds a row:
30
+
31
+ ```
32
+ users
33
+ id
34
+
35
+ user_statuses
36
+ id
37
+ user_id
38
+ status
39
+ created_at
40
+ ```
41
+
42
+ `user_statuses` is both the history and the source of truth: its
43
+ most recent row is the current state. PostgreSQL keeps this
44
+ efficient:
45
+
46
+ - **Reading the current state is fast.** Only the latest row per
47
+ record is fetched, through an index, no matter how long the history
48
+ grows. It loads as a regular ActiveRecord object, for one record or
49
+ many, without N+1 queries. For many records, this uses a
50
+ `LEFT JOIN LATERAL`.
51
+ - **Transitions stay consistent.** Each transition is checked against
52
+ the allowed transitions, and concurrent transitions for the same
53
+ record run one at a time, so simultaneous requests can't leave a
54
+ record in an invalid state. This uses `SELECT ... FOR UPDATE` on
55
+ the user's row.
56
+
57
+ AppendTransitions also comes with the most common functionality
58
+ you'd need from a state machine: allowed transitions are enforced,
59
+ and concurrent transitions can't corrupt the state. With it, you may
60
+ not need a state machine gem at all. AppendTransitions leaves out
61
+ callbacks, guards, events and DSLs, has no dependencies beyond
62
+ ActiveRecord, and no monkey patches: you get a few methods on your
63
+ model and plain ActiveRecord objects back.
64
+
65
+ Instead of hiding side effects in callbacks on the state, keep them
66
+ in the code that requests the transition, such as a service object.
67
+ When they need to run inside the lock, pass a block to
68
+ `transition_status`.
69
+
70
+ For the reasoning and benchmarks behind this design, see
71
+ [Modeling State Transitions in Postgres][modeling-post] and
72
+ [Inserting State Transitions in Postgres][inserting-post].
73
+
74
+ [modeling-post]: https://thoughtbot.com/blog/modeling-state-transitions-in-postgres
75
+ [inserting-post]: https://thoughtbot.com/blog/inserting-state-transitions-in-postgres
76
+
77
+ ## When to use something else
78
+
79
+ Appending a row per transition fits states that change a handful of
80
+ times over a record's life and whose history matters, like most
81
+ business workflows. Consider something else when:
82
+
83
+ - **The value changes constantly.** For things like chat presence
84
+ or a progress percentage, every change adds a row and an index
85
+ entry that nobody will query. A column is simpler. If you do need
86
+ that history at high volume, like device telemetry, use a store
87
+ built for time series.
88
+ - **You only need an audit trail.** For debugging or compliance
89
+ across many models, a generic tool like
90
+ [PaperTrail](https://github.com/paper-trail-gem/paper_trail) tracks
91
+ changes everywhere with less setup. It stores changes as serialized
92
+ data, which is fine for an audit log but awkward to query, so it
93
+ complements state history rather than replacing it.
94
+
95
+ ## Requirements
96
+
97
+ - PostgreSQL
98
+ - Ruby 3.2+
99
+ - ActiveRecord 7.0+
100
+
101
+ The generator needs Rails; the gem itself only depends on
102
+ ActiveRecord.
103
+
104
+ Other databases aren't supported (see [Limitations](#limitations)).
105
+
106
+ ## Installation
107
+
108
+ Add to your Gemfile:
109
+
110
+ ```ruby
111
+ gem "append_transitions"
112
+ ```
113
+
114
+ Then run:
115
+
116
+ ```bash
117
+ bundle install
118
+ ```
119
+
120
+ ## Usage
121
+
122
+ ### The state table
123
+
124
+ The examples track a user's status, but anything with a lifecycle
125
+ works, like an order's fulfillment or a document's review. The model
126
+ whose state is tracked, `User` here, is the *parent*.
127
+
128
+ ```bash
129
+ bin/rails generate append_transitions:state User status
130
+ ```
131
+
132
+ This creates a migration (and the model, below):
133
+
134
+ ```ruby
135
+ class CreateUserStatuses < ActiveRecord::Migration[8.1]
136
+ def change
137
+ create_table :user_statuses do |t|
138
+ t.references :user, null: false, foreign_key: true, index: false
139
+ t.string :status, null: false
140
+ t.timestamps
141
+ end
142
+
143
+ add_index :user_statuses, [:user_id, :created_at, :id],
144
+ order: {created_at: :desc, id: :desc},
145
+ include: :status
146
+ end
147
+ end
148
+ ```
149
+
150
+ The index lets PostgreSQL find each user's latest status without
151
+ scanning the table, and `include` (ActiveRecord 7.1+) lets it answer
152
+ from the index alone.
153
+
154
+ Together, the two arguments, `User` and `status`, form the table
155
+ name, `user_statuses`, and the state model, `UserStatus`.
156
+
157
+ By default, the state column is named `status`, so our first command
158
+ could be written with an explicit `--state-column` option:
159
+
160
+ ```bash
161
+ bin/rails generate append_transitions:state User status --state-column=status
162
+ ```
163
+
164
+ You can also use a different name:
165
+
166
+ ```bash
167
+ # DocumentReview model, document_reviews table with a stage column,
168
+ # and current_review on Document
169
+ bin/rails generate append_transitions:state Document review --state-column=stage
170
+ ```
171
+
172
+ The migration follows your app's primary key type (`bigint` unless
173
+ you've configured another), which you can change with
174
+ `--primary-key-type`, just like in Rails. You can also pass
175
+ `--database`, which puts the migration in that database and makes
176
+ the model inherit from its abstract class (e.g. `AnimalsRecord`),
177
+ creating the class if it's missing.
178
+
179
+ A namespaced parent gets a namespaced model and table:
180
+
181
+ ```bash
182
+ # Admin::UserStatus model and admin_user_statuses table
183
+ bin/rails generate append_transitions:state Admin::User status
184
+ ```
185
+
186
+ If you write the migration yourself and leave out the index, the
187
+ [missing index check](#missing-index-check) warns you the first
188
+ time the state is read and tells you which index to add.
189
+
190
+ ### The models
191
+
192
+ The generator also creates the state model:
193
+
194
+ ```ruby
195
+ class UserStatus < ApplicationRecord
196
+ belongs_to :user
197
+
198
+ def readonly? = super || (persisted? && !destroyed_by_association)
199
+ end
200
+ ```
201
+
202
+ Rows are never updated or deleted. `readonly?` makes persisted
203
+ records read-only so that `update!` and `destroy` raise
204
+ `ActiveRecord::ReadOnlyRecord`. Each part of the method has a role:
205
+
206
+ - `persisted?` still lets new rows be created.
207
+ - `!destroyed_by_association` lets the parent destroy its rows
208
+ through `has_many ..., dependent: :destroy`.
209
+ - `super` keeps `readonly!` working.
210
+
211
+ > [!WARNING]
212
+ > The check runs on individual records, so bulk methods like
213
+ > `update_all` and `delete_all` skip it.
214
+
215
+ The generator doesn't change the parent model. It prints an
216
+ `include AppendTransitions::HasCurrent` to paste into it, with
217
+ placeholder states to replace with your own, for example:
218
+
219
+ ```ruby
220
+ class User < ApplicationRecord
221
+ include AppendTransitions::HasCurrent.new(
222
+ :status,
223
+ class_name: "UserStatus",
224
+ initial_state: :pending,
225
+ transitions: {
226
+ pending: [:approved, :denied],
227
+ denied: :pending
228
+ }
229
+ )
230
+ end
231
+ ```
232
+
233
+ `initial_state` is the only state a user without any rows can
234
+ transition to. Each key in `transitions` lists the states it can
235
+ move to.
236
+
237
+ ### Reading the current state
238
+
239
+ ```ruby
240
+ user.current_status # => #<UserStatus status: "approved">
241
+ user.current_status.status # => "approved"
242
+ ```
243
+
244
+ `current_status` returns `nil` for a user without any rows. The
245
+ result is cached on the record, like an association. `reload` and
246
+ `transition_status` (see [Transitioning](#transitioning)) clear it.
247
+
248
+ States are declared as symbols, but the column holds strings, so
249
+ `status` reads back as `"approved"`. `transition_status` accepts
250
+ either, as do the keys and values in `transitions`.
251
+
252
+ ### Querying many records
253
+
254
+ `with_current_status` loads each user's current status in the same
255
+ query, so iterating doesn't trigger extra queries:
256
+
257
+ ```ruby
258
+ User.with_current_status.each do |user|
259
+ user.current_status # no extra query
260
+ end
261
+ ```
262
+
263
+ Filter by the current status with a hash, as with any joined table:
264
+
265
+ ```ruby
266
+ User.with_current_status.where(current_status: {status: "approved"})
267
+ ```
268
+
269
+ It returns a regular relation, so it chains with `where`, `count`,
270
+ `pluck`, `find_each` and friends.
271
+
272
+ > [!WARNING]
273
+ > The current status loads from columns `with_current_status` adds
274
+ > to the query. Replacing them, e.g. with `reselect`, brings back
275
+ > N+1 queries: `current_status` queries once per record instead.
276
+
277
+ ### Transitioning
278
+
279
+ ```ruby
280
+ user.transition_status(:pending) # => #<UserStatus status: "pending">
281
+ user.transition_status(:approved) # => #<UserStatus status: "approved">
282
+ user.transition_status(:pending)
283
+ # => raises AppendTransitions::InvalidTransition:
284
+ # Cannot transition from approved to pending
285
+ ```
286
+
287
+ `transition_status` locks the user's row, reads the current status,
288
+ checks the transition, and inserts the new row, all in one
289
+ transaction. A concurrent transition for the same user waits for the
290
+ lock, then sees the updated status. The new row's `created_at` is
291
+ always after the current one's, even if another server's clock is
292
+ ahead. The user isn't reloaded, so unsaved changes on it are kept.
293
+
294
+ Pass a block to run code inside the same transaction, after the
295
+ insert. The block receives the new record. If the transition is
296
+ invalid, the block doesn't run. If the block raises, the insert is
297
+ rolled back:
298
+
299
+ ```ruby
300
+ user.transition_status(:approved) do |status|
301
+ Notification.create!(user:, message: "Approved at #{status.created_at}")
302
+ end
303
+
304
+ UserMailer.approved(user).deliver_later
305
+ ```
306
+
307
+ Send emails and other side effects that can't be rolled back after
308
+ the call, so they only happen once the transition is committed.
309
+ If two requests approve the same user at once, the second waits for
310
+ the lock, finds the user already approved and raises
311
+ `AppendTransitions::InvalidTransition`, so the email only goes out
312
+ once.
313
+
314
+ ### Options
315
+
316
+ | Option | Default | Description |
317
+ |-----------------|----------------------------------|--------------------------------------------------|
318
+ | `class_name` | (required) | The state model |
319
+ | `initial_state` | (required) | The first state a record can transition to |
320
+ | `transitions` | `{}` | Allowed transitions, from a state to one or many |
321
+ | `foreign_key` | inferred, e.g. `user_id` | The state table's column pointing to the parent |
322
+ | `state_column` | `:status` | The state table's column holding the state |
323
+ | `order` | `{created_at: :desc, id: :desc}` | The `ORDER BY` that puts the current row first |
324
+
325
+ The first argument to `HasCurrent.new` names the methods it adds
326
+ (the generator fills it in from its own second argument). `:status`
327
+ gives `current_status`, `transition_status` and
328
+ `with_current_status`, so a model can track more than one state.
329
+ Here, the state lives in a `stage` column:
330
+
331
+ ```ruby
332
+ class Document < ApplicationRecord
333
+ include AppendTransitions::HasCurrent.new(
334
+ :review,
335
+ class_name: "DocumentReview",
336
+ state_column: :stage,
337
+ initial_state: :requested,
338
+ transitions: {requested: [:accepted, :rejected]}
339
+ )
340
+ end
341
+
342
+ # Example usage
343
+ document = Document.find(27)
344
+ document.transition_review(:requested)
345
+ puts document.current_review.stage # prints "requested"
346
+
347
+ Document.with_current_review.where(current_review: {stage: "requested"}).each do |doc|
348
+ puts doc.current_review.stage # no extra query
349
+ end
350
+ ```
351
+
352
+ The default `order` configuration, which the example above leaves
353
+ out, breaks ties on `created_at` with `id`, since `created_at` isn't
354
+ unique. `order` must be a hash of columns to directions, since the
355
+ recommended index is built from it. If you change `order`, keep the
356
+ index in the same order (edit the generated migration).
357
+
358
+ ### Missing index check
359
+
360
+ The first time `current_*` or `with_current_*` runs, AppendTransitions
361
+ checks that the state table has an index starting with the foreign
362
+ key, followed by the `order` columns (`user_id, created_at, id` by
363
+ default). Without one, lookups of the current state, including the
364
+ one `transition_*` makes, slow down as the history grows. By default
365
+ it prints a warning with the `add_index` call to put in a migration:
366
+
367
+ ```ruby
368
+ add_index :user_statuses, [:user_id, :created_at, :id],
369
+ order: {created_at: :desc, id: :desc}, include: :status
370
+ ```
371
+
372
+ The check skips partial and expression indexes, and doesn't look at
373
+ sort directions or `include`. PostgreSQL can read an index in either
374
+ direction, and an index without `include` still finds the latest
375
+ row, only with an extra read of the table.
376
+
377
+ To raise instead of warning:
378
+
379
+ ```ruby
380
+ # config/initializers/append_transitions.rb
381
+ AppendTransitions.configure do |config|
382
+ config.on_missing_index = :raise
383
+ end
384
+ ```
385
+
386
+ ## Limitations
387
+
388
+ - **PostgreSQL only.** AppendTransitions is only tested on
389
+ PostgreSQL. On SQLite, `with_current_status` fails with an SQL
390
+ syntax error. `current_status` and `transition_status` still run,
391
+ but SQLite has no `FOR UPDATE` row locks, so concurrent transitions
392
+ aren't serialized there.
393
+ - **Extra attributes on the parent.** `with_current_status` selects
394
+ the state columns as `current_status_id`, `current_status_status`
395
+ and so on. They show up in the parent's `attributes`, `as_json` and
396
+ `inspect`. ActiveRecord has no public way to hide selected columns.
397
+ - **Writes that bypass `transition_*`.** Creating rows directly, such
398
+ as `UserStatus.create!`, skips both the lock and the transition
399
+ check. Validation lives in the application, not the database.
400
+ - **Changes from other processes.** Like an association,
401
+ `current_status` is cached per record. A transition made elsewhere
402
+ isn't visible until you `reload`.
403
+ - **Composite primary keys** on the parent aren't supported.
404
+ - **Separate databases.** The parent and the state table must share a
405
+ database. Otherwise the lock and the insert run in separate
406
+ transactions, so a failing block doesn't roll back the insert.
407
+
408
+ ## Stability
409
+
410
+ AppendTransitions is intentionally minimal. It builds on long-standing
411
+ ActiveRecord and PostgreSQL features, so we expect it to change
412
+ rarely, and mostly in additive ways.
413
+
414
+ One part relies on an ActiveRecord internal: `with_current_*`
415
+ hydrates records by reading `@records` on the relation, as the
416
+ Goldiloader and Bullet gems do. CI runs every supported ActiveRecord
417
+ version to catch changes there.
418
+
419
+ ## Development
420
+
421
+ After checking out the repo, run `bin/setup` to install
422
+ dependencies. The tests need a local PostgreSQL database named
423
+ `append_transitions_test`:
424
+
425
+ ```bash
426
+ createdb append_transitions_test
427
+ bundle exec rake
428
+ ```
429
+
430
+ `bundle exec rake` runs the tests and the linter. To test against
431
+ another ActiveRecord version, point `BUNDLE_GEMFILE` at one of the
432
+ files in `gemfiles/`:
433
+
434
+ ```bash
435
+ BUNDLE_GEMFILE=gemfiles/activerecord_7.0.gemfile bundle install
436
+ BUNDLE_GEMFILE=gemfiles/activerecord_7.0.gemfile bundle exec rake test
437
+ ```
438
+
439
+ ## Contributing
440
+
441
+ See the [CONTRIBUTING] document.
442
+ Thank you, [contributors]!
443
+
444
+ [CONTRIBUTING]: CONTRIBUTING.md
445
+ [contributors]: https://github.com/thoughtbot/append_transitions/graphs/contributors
446
+
447
+ ## License
448
+
449
+ AppendTransitions is Copyright (c) thoughtbot, inc.
450
+ It is free software, and may be redistributed
451
+ under the terms specified in the [LICENSE] file.
452
+
453
+ [LICENSE]: /LICENSE
454
+
455
+ ## About thoughtbot
456
+
457
+ ![thoughtbot](https://thoughtbot.com/thoughtbot-logo-for-readmes.svg)
458
+
459
+ This repo is maintained and funded by thoughtbot, inc.
460
+ The names and logos for thoughtbot are trademarks of thoughtbot, inc.
461
+
462
+ We love open source software!
463
+ See [our other projects][community].
464
+ We are [available for hire][hire].
465
+
466
+ [community]: https://thoughtbot.com/community?utm_source=github
467
+ [hire]: https://thoughtbot.com/hire-us?utm_source=github
data/Rakefile ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.test_files = FileList["test/**/*_test.rb"]
9
+ end
10
+
11
+ require "standard/rake"
12
+
13
+ task default: %i[test standard]
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ class Configuration
5
+ VALID_ON_MISSING_INDEX = %i[raise warn].freeze
6
+
7
+ attr_reader :on_missing_index
8
+
9
+ def initialize
10
+ @on_missing_index = :warn
11
+ end
12
+
13
+ def on_missing_index=(value)
14
+ unless VALID_ON_MISSING_INDEX.include?(value)
15
+ options = VALID_ON_MISSING_INDEX.join(", ")
16
+ message = "on_missing_index must be one of: #{options}"
17
+
18
+ raise ArgumentError, message
19
+ end
20
+
21
+ @on_missing_index = value
22
+ end
23
+ end
24
+
25
+ class << self
26
+ def configuration
27
+ @configuration ||= Configuration.new
28
+ end
29
+
30
+ def configure
31
+ yield configuration
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ # Added to with_current_* relations via .extending. A bare count would
5
+ # wrap the aliased select in COUNT(...), which is invalid SQL, so it
6
+ # counts all rows instead.
7
+ module CountAll
8
+ def count(column_name = nil, &block)
9
+ return super if block
10
+
11
+ super(column_name || :all)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ class CurrentQuery
5
+ include ForeignKey
6
+
7
+ def initialize(class_name:, order:, foreign_key:)
8
+ @class_name = class_name
9
+ @foreign_key = foreign_key
10
+ @order = order
11
+ end
12
+
13
+ def call(record)
14
+ @class_name.constantize
15
+ .where(fk_for(record.class) => record.id)
16
+ .order(@order)
17
+ .first
18
+ end
19
+ end
20
+ end