recorder 1.3.0 → 2.0.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.
data/README.md CHANGED
@@ -69,31 +69,185 @@ end
69
69
 
70
70
  Recorder supports the following options:
71
71
 
72
- * `ignore: [array]` - attributes that are ignored on logging;
73
- * `only: [array]` - only these attributes are logged, other attributes are ingored;
74
- * `associations: {hash} (hash)` - allows to set what associations will be logged alongside with the model. For each association you can also set ignore and only options;
75
- * `async: bool` - a logging strategy (true - asynchronous, false - synchronous).
72
+ * `ignore: [array]` - attributes that are ignored on logging. Replaces `Recorder.config.ignore` for this model rather than adding to it;
73
+ * `only: [array]` - only these attributes are logged, other attributes are ignored. `Recorder.config.ignore` does not apply, so a listed attribute is logged even if the global list ignores it. Takes precedence over `ignore:`;
74
+ * `associations: {hash} (hash)` - allows to set what associations will be logged alongside with the model, as a snapshot on `create` and `destroy`. For each association you can also set ignore and only options, which follow the same rules; an association given neither falls back to `Recorder.config.ignore`. Only singular associations, `belongs_to` and `has_one`, are recorded: a collection (`has_many`, `has_and_belongs_to_many`), or a name that is not an association, is skipped and logged as a warning through the model's logger, once per model and process. On a subclass, a name that only a sibling class declares is skipped without a warning;
75
+ * `if: Symbol | Proc`, `unless: Symbol | Proc` - a condition the record has to meet, or
76
+ must not meet, for a change to be recorded. See [Conditions](#conditions);
77
+ * `changes: Proc | Symbol` - extra entries to merge into a revision's `changes`. A Proc
78
+ is evaluated on the record, a Symbol names a method on it; both receive the event
79
+ (`:create`, `:update` or `:destroy`) and return a hash of `name => [old, new]`, or
80
+ `nil` for nothing. Anything else raises `ArgumentError` where `recorder` is called.
81
+
82
+ The entries are merged after `only:` and `ignore:` have been applied, so those
83
+ filters never drop them, and a key that matches an attribute replaces that
84
+ attribute's entry. An update that reports only custom entries still records a
85
+ revision.
86
+
87
+ Inside the callback, read `saved_changes` and `saved_change_to_<attribute>?`, not
88
+ `<attribute>_changed?`: on `:create` and `:update` the callback runs from
89
+ `after_create`/`after_update`, where the dirty state has already been reset. On
90
+ `:destroy` it runs from `after_destroy`, where `destroy` has reset nothing:
91
+ `saved_changes` still holds the record's last save, not the deletion.
92
+
93
+ `Recorder::Changeset` rebuilds the previous and next versions by assigning each
94
+ change onto a copy of the record, and skips what it cannot assign: a key that is
95
+ not an attribute, and any value that is not a two-element `[old, new]` pair. To display such
96
+ a key, define `previous_<key>`/`next_<key>` on the model's changeset class, and
97
+ pick a name that `Recorder::Changeset` does not already answer to.
98
+
99
+ Option names can be symbols or strings, in `recorder` and in each association's
100
+ options, and so can association names. `recorder` raises `ArgumentError` for
101
+ any other option, so a misspelt one fails where it is written, for an option or
102
+ association given both as a symbol and as a string, and for an association name
103
+ that is neither. `async:` and `delay:` raise too, with a message saying
104
+ asynchronous recording was removed in 2.0.0.
105
+
106
+ `Model.recorder_options` returns the declared options with symbol keys, the
107
+ association names included, frozen.
108
+
109
+ A model that needs to decide its options per record can define
110
+ `recorder_options` as an instance method. It replaces what was passed to
111
+ `recorder` rather than merging with it, so it has to return every option the
112
+ model needs, with symbol keys; its result is used as it is, unchecked. `if:`
113
+ and `unless:` are the exception: they belong to the callbacks, and an override
114
+ cannot change them (see [Conditions](#conditions)):
76
115
 
77
- These per-model options do not reach the recorder yet — see [Known issues](#known-issues).
78
- Until they do, every observed model records a full attribute snapshot, filtered
79
- only by the global `Recorder.config.ignore`.
116
+ ```ruby
117
+ def recorder_options
118
+ {ignore: %i[identifier], changes: :extra_changes}
119
+ end
120
+ ```
121
+
122
+ #### Conditions
123
+
124
+ `if:` and `unless:` decide per record whether a change is recorded, as they do
125
+ on a Rails callback:
126
+
127
+ ```ruby
128
+ class Post < ActiveRecord::Base
129
+ include ::Recorder::Observer
130
+
131
+ recorder ignore: %i[views_count], if: :published?, unless: ->(post) { post.imported? }
132
+ end
133
+ ```
134
+
135
+ A Symbol names a method on the record, public or private; a misspelt one
136
+ raises `NoMethodError` from the first save, which rolls it back. A Proc takes
137
+ one argument, the record, or none, in which case it is evaluated on the record.
138
+ A change is recorded when `if:` returns a truthy value and `unless:` a falsy
139
+ one, and `nil` means no condition, as on a Rails callback.
140
+
141
+ `recorder` raises `ArgumentError` for any other value: a Proc with other
142
+ parameters, optional or splat ones included, since Rails would not pass it the
143
+ record, an Array, or an object that responds to `call`. For such an object,
144
+ pass `Policy.method(:call).to_proc`.
145
+
146
+ The condition applies to create, update and destroy alike. It runs only while
147
+ recording is on, so it cannot turn recording back on for a change
148
+ `recorder_disabled!` or `Recorder.enabled = false` skips.
149
+
150
+ It runs after the change, in the same `after_create`, `after_update` and
151
+ `after_destroy` callbacks as `changes:`, so the notes there on `saved_changes`
152
+ apply. It sees the record as saved, so a change that makes it false is not
153
+ recorded: with `if: :published?`, unpublishing a post writes no revision, and
154
+ its history ends on the last published state. To record the change that
155
+ leaves the condition, test the value before the save too:
156
+
157
+ ```ruby
158
+ recorder if: -> { published? || status_previously_was == 'published' }
159
+ ```
160
+
161
+ On destroy, `status_previously_was` reads the record's last save, and the
162
+ associated records `dependent: :destroy` removes are already gone.
163
+
164
+ To vary the condition by event, `destroyed?` is true on destroy, and otherwise
165
+ `previously_new_record?` tells a create from an update. `previously_new_record?`
166
+ stays true when the record that was created is then destroyed, so check
167
+ `destroyed?` first. This records a create only for a featured post:
168
+
169
+ ```ruby
170
+ recorder if: -> { destroyed? || !previously_new_record? || featured? }
171
+ ```
172
+
173
+ `recorder` alone sets the condition. A subclass inherits it, and `if:` or
174
+ `unless:` returned by a `recorder_options` override have no effect, so an
175
+ override that builds a new hash keeps it. To vary the condition by subclass,
176
+ name a method and override that method.
177
+
178
+ `Recorder::Tape.new(record).record_update` and its `record_create` and
179
+ `record_destroy` siblings do not check the condition: calling one is the
180
+ decision to record. They still write nothing while recording is off.
181
+
182
+ #### Subclasses
183
+
184
+ A subclass, STI or not, records under the options its parent passed to
185
+ `recorder` and needs no declaration of its own. `recorder` can be called once per
186
+ class hierarchy, in the topmost class that records: calling it again, in the same
187
+ class, a subclass or a parent, raises `ArgumentError`. So does a declaration that
188
+ runs twice on one class, such as one in a `to_prepare` block on a class that is
189
+ not reloaded. A subclass that needs different options defines
190
+ `recorder_options`, public or private, and can build on the parent's with `super`:
191
+
192
+ ```ruby
193
+ class Bond < Instrument
194
+ def recorder_options
195
+ super.merge(ignore: [*super[:ignore], :coupon])
196
+ end
197
+ end
198
+ ```
199
+
200
+ `super` returns a copy of the parent's options, which the override can change
201
+ in place or build on. The result is applied as if it had been declared, except
202
+ for `if:` and `unless:`, which an override cannot change. A
203
+ `recorder_options` class method that calls `super` gets the frozen options every
204
+ subclass shares, so it builds a new hash, such as `super.merge(...)`; one that
205
+ changes them in place raises `FrozenError` from the first save that reads it,
206
+ which rolls that save back. The usual
207
+ rules hold: `only:` takes precedence over `ignore:`, so adding to `ignore:` has
208
+ no effect under a parent that declares `only:`, and an `ignore:` replaces
209
+ `Recorder.config.ignore`, so a subclass adding one under a parent that declares
210
+ none has to repeat the global list.
80
211
 
81
212
  ### Global configuration
82
213
 
83
214
  ```ruby
84
215
  Recorder.config do |config|
85
216
  config.ignore = %i[created_at updated_at]
86
- config.async = false
87
- config.sidekiq_options = {queue: 'recorder', retry: 10, backtrace: true}
88
217
  end
89
218
  ```
90
219
 
91
- `ignore` defaults to `[]`, `async` to `false`, and `sidekiq_options` to the hash
92
- shown above.
220
+ `ignore` defaults to `[]`.
221
+
222
+ `ignore` applies only to models, and associations, that declare neither `only:`
223
+ nor `ignore:`. A model that declares either uses its own list alone, so to keep
224
+ the global list and add to it, repeat it:
225
+
226
+ ```ruby
227
+ recorder ignore: [*Recorder.config.ignore, :internal_id]
228
+ ```
229
+
230
+ This reads the global list when the model loads, so configure `Recorder` in an
231
+ initializer.
93
232
 
94
- There are two strategies for logging: synchronous and asynchronous. When the synchronous strategy is used, a revision record is saved immediately after a model is saved, and the async strategy moves creating of revision records to [Sidekiq](https://github.com/sidekiq/sidekiq). Under the async
95
- strategy the revision is enqueued to `Recorder::Sidekiq::RevisionsWorker` two
96
- seconds out; the worker is loaded by the railtie when `Sidekiq` is defined.
233
+ ### When a revision is written
234
+
235
+ A revision is written from the model's `after_create`, `after_update` and
236
+ `after_destroy` callbacks, in the same database transaction as the save. The
237
+ record and its revision commit together, and a save that rolls back leaves no
238
+ revision behind.
239
+
240
+ A revision that cannot be written fails the save: it raises, and the save rolls
241
+ back, along with any transaction around it that does not rescue the error. This
242
+ holds for `save` and `update` as much as for `save!`, and for `destroy`. A
243
+ revision that fails validation, or that a callback on `Recorder::Revision`
244
+ halts, raises `Recorder::RevisionNotSaved`, a subclass of
245
+ `ActiveRecord::RecordNotSaved` whose `record` is the revision. A database error
246
+ raises as it would from any other write.
247
+
248
+ Nothing but the error rolls the save back. A transaction of your own that
249
+ rescues it, or rescues `ActiveRecord::RecordNotSaved`, commits the record
250
+ without its revision. Let the error propagate, or re-raise it.
97
251
 
98
252
  ### Recording the current user
99
253
 
@@ -110,6 +264,34 @@ The concern reads `current_user`; override `recorder_user_id` to name a differen
110
264
  method. Override `recorder_meta` to store a hash alongside every revision. A
111
265
  revision without a user is valid — `user_id` stays `nil`.
112
266
 
267
+ `revision.user` loads a `User` model. If your user model has another name,
268
+ declare the association again in a `to_prepare` block, so that it picks up the
269
+ reloaded class in development:
270
+
271
+ ```ruby
272
+ # config/initializers/recorder.rb
273
+ Rails.application.config.to_prepare do
274
+ Recorder::Revision.belongs_to :user, class_name: 'Account', optional: true
275
+ end
276
+ ```
277
+
278
+ Declaring it on every reload replaces the association each time. Keep
279
+ `optional: true`. Without it, `belongs_to_required_by_default` makes the user
280
+ required: a change made with no user, or by a user since deleted, raises
281
+ `Recorder::RevisionNotSaved`, and the save rolls back.
282
+
283
+ A revision's `action_date` is today in the application's time zone,
284
+ `Date.current`. To date revisions otherwise, such as an import replaying past
285
+ changes, set it yourself; it holds for the rest of the request or thread:
286
+
287
+ ```ruby
288
+ Recorder.info = {action_date: Date.new(2020, 1, 1)}
289
+ ```
290
+
291
+ `created_at` is always when the revision was written. `Recorder.info` raises
292
+ `ArgumentError` for it and for the other columns Recorder writes itself: `id`,
293
+ `item_type`, `item_id`, `event` and `data`.
294
+
113
295
  ### Turning recording off
114
296
 
115
297
  `Recorder::Manager` suspends recording for the current request or thread:
@@ -126,9 +308,18 @@ class Importer
126
308
  end
127
309
  ```
128
310
 
129
- The block form re-enables recording on the way out, including when the block
130
- raises. Called without a block, `recorder_disabled!` stays in effect until
131
- `recorder_enabled!`.
311
+ The block form restores the state it found on the way out, including when the
312
+ block raises, so a block nested in another leaves recording off. Called without
313
+ a block, `recorder_disabled!` stays in effect until `recorder_enabled!`. That
314
+ state is cleared when a web request ends, but not reliably between background
315
+ jobs, where it would carry over to later jobs on the same thread; use the block
316
+ form there.
317
+
318
+ `Recorder.enabled = false` switches recording off for the whole process, every
319
+ thread included, until `Recorder.enabled = true`. It suits a one-off script,
320
+ such as a backfill or a data migration; inside a running app it would stop the
321
+ trail for every request at once, so use `recorder_disabled!` there. A change is
322
+ recorded only while both are on.
132
323
 
133
324
  ### Reading revisions
134
325
 
@@ -143,6 +334,57 @@ revision.user_id
143
334
  revision.action_date
144
335
  ```
145
336
 
337
+ `data` carries a complete attribute snapshot on every event, not only what
338
+ changed:
339
+
340
+ - `attributes` — every attribute of the record, with the values it last loaded
341
+ from or saved to the database, filtered by the model's `only:` or `ignore:`
342
+ and, failing those, by `Recorder.config.ignore`. Always present. An
343
+ attribute assigned and never saved is not recorded: after a `create` or an
344
+ `update` memory and database agree, and a `destroy` revision holds the row
345
+ as the record last saw it, not an assignment made since.
346
+ - `changes` — the same filter applied to `saved_changes`, as
347
+ `name => [old, new]`, plus any entries from `changes:`. On `destroy`, only
348
+ the entries from `changes:`. Omitted when that leaves nothing.
349
+ - `associations` — on `create` and `destroy`, an `attributes` snapshot of each
350
+ association named in `associations:`, filtered by that association's own
351
+ `only:` or `ignore:`, with the same rule for unsaved assignments. Omitted on
352
+ `update`, when no named association is set, and on `destroy` when the
353
+ associated record was never saved. An associated record's changes are not
354
+ recorded: they belong to its own revisions, and replacing a `belongs_to`
355
+ target shows up as the foreign key in `changes`, unless `only:` or `ignore:`
356
+ leaves it out.
357
+
358
+ The snapshot is the contract, not an accident of the implementation: a
359
+ revision's `attributes` are self-contained, so reconstructing a record at a
360
+ point in time does not mean replaying every prior diff. It is also what keeps a
361
+ `destroy` revision useful, since the row it describes is gone. Association
362
+ snapshots exist only on `create` and `destroy` revisions.
363
+
364
+ An `update` records a revision only when the record reports a change; `create`
365
+ and `destroy` always record one.
366
+
367
+ `item_type` holds the model's `polymorphic_name`, the value Active Record
368
+ writes to any polymorphic association, so `revisions`, `includes(:revisions)`
369
+ and `Recorder::Revision.where(item: record)` all find a record's revisions. For
370
+ an STI subclass that is the base class: a `Bond < Instrument` is recorded as
371
+ `"Instrument"`, `revision.item` loads it back as a `Bond`, and the subclass name
372
+ is in the snapshot's inheritance column (`type` by default) unless `only:` or
373
+ `ignore:` leaves it out.
374
+
375
+ Revisions written before 2.0.0 hold the subclass name, so `revisions` does not
376
+ find them. Rewriting them is up to the app; this does it for every subclass
377
+ whose class still exists:
378
+
379
+ ```ruby
380
+ Recorder::Revision.distinct.pluck(:item_type).each do |type|
381
+ model = type.safe_constantize
382
+ next unless model.respond_to?(:polymorphic_name) && model.polymorphic_name != type
383
+
384
+ Recorder::Revision.where(item_type: type).update_all(item_type: model.polymorphic_name)
385
+ end
386
+ ```
387
+
146
388
  `#item_changeset` wraps `data['changes']` in a `Recorder::Changeset`, which reads
147
389
  the values back as the model's own types:
148
390
 
@@ -156,7 +398,9 @@ changeset.human_attribute_name(:title)
156
398
  changeset.previous_version # a copy of the record with the old values
157
399
  ```
158
400
 
159
- Changed associations are reachable the same way:
401
+ Revisions written before 2.0.0 can also hold an association's `changes`,
402
+ reachable the same way. `changed_associations` lists the associations that hold
403
+ some, and `association_changeset` returns `nil` for one that does not:
160
404
 
161
405
  ```ruby
162
406
  revision.changed_associations # ["author"]
@@ -168,20 +412,98 @@ as `"#{model}Changeset"` — or point at another one with a
168
412
  `recorder_changeset_class` class method on the model. Otherwise
169
413
  `Recorder::Changeset` is used.
170
414
 
415
+ ## Upgrading to 2.0.0
416
+
417
+ 2.0.0 changes what Recorder writes to `recorder_revisions`. Existing rows are
418
+ not rewritten, so a trail that spans the upgrade holds revisions of both
419
+ shapes. [CHANGELOG.md](CHANGELOG.md) lists every change; this is the order to
420
+ act on them in.
421
+
422
+ ### Before upgrading
423
+
424
+ If `Recorder.config.async` is `true`, set it to `false` on 1.x, deploy that, and
425
+ let the revision jobs already pushed finish, the scheduled and retrying ones
426
+ included. 2.0.0 removes the worker, so a job still queued then fails and its
427
+ revision is never written.
428
+
429
+ ### When upgrading
430
+
431
+ These raise until they are changed. A `recorder` declaration raises when its
432
+ class loads, so booting with `config.eager_load = true` finds every one:
433
+
434
+ - Remove `async:` and `delay:` from `recorder`, and any assignment to
435
+ `Recorder.config.async` or `Recorder.config.sidekiq_options`.
436
+ - Call `recorder` once per class hierarchy, in the topmost class that records.
437
+ A subclass that declared it again for other options defines a
438
+ `recorder_options` instance method instead; see [Subclasses](#subclasses).
439
+ - Fix any option `recorder` does not know, in its own options or in an
440
+ association's, such as a misspelt `ignores:`.
441
+ - Stop setting `created_at`, `id`, `item_type`, `item_id`, `event` or `data`
442
+ through `Recorder.info`. To date revisions otherwise, set `action_date`.
443
+ - A `recorder_options` class method that changes `super` in place raises
444
+ `FrozenError` from the first save; build a new hash, such as
445
+ `super.merge(...)`.
446
+ - Replace `recorder_dirty?`, `recorder_record?` and `@recorder_dirty = false`:
447
+ declare a rule about the model's records with `recorder if:` or `unless:`
448
+ (see [Conditions](#conditions)), and skip one call's changes with
449
+ `recorder_disabled! { record.save }`. Drop calls to
450
+ `Recorder.active_record_protected_attributes?`.
451
+
452
+ These record differently without raising, so check each against what the app
453
+ expects:
454
+
455
+ - The options passed to `recorder` apply. Since 1.2.2 every model recorded under
456
+ the global configuration instead. A model that declares `only:` or `ignore:`
457
+ records a smaller snapshot, and an update touching only the attributes it
458
+ leaves out writes no revision. A per-model `ignore:` replaces
459
+ `Recorder.config.ignore`, so repeat the global list to keep it, as in
460
+ `ignore: [*Recorder.config.ignore, :token]`. `associations:` adds snapshots to
461
+ create and destroy revisions.
462
+ - A subclass records under its parent's options, and an STI subclass's
463
+ revisions store the base class name in `item_type`.
464
+ - `Recorder.enabled = false` switches recording off, so a script that sets it,
465
+ such as a backfill, writes no revisions.
466
+ - A revision that cannot be written fails the save with
467
+ `Recorder::RevisionNotSaved` and rolls it back, where it used to be dropped.
468
+ That includes validations and callbacks the app added to
469
+ `Recorder::Revision`, and a `Revision#user` declared again without
470
+ `optional: true`; see [Recording the current user](#recording-the-current-user).
471
+ - An app that loads a gem defining `ProtectedAttributes`, such as
472
+ `protected_attributes_continued`, starts recording. Every revision used to
473
+ fail validation and be dropped.
474
+ - `Model.recorder_options` has symbol keys, so `recorder_options['ignore']`
475
+ returns `nil`.
476
+ - `action_date` is today in the application's time zone, `Date.current`, where
477
+ it was the server's `Date.today`.
478
+
479
+ ### After upgrading
480
+
481
+ Review what reads the trail:
482
+
483
+ - Revisions an STI subclass wrote before the upgrade hold the subclass name, so
484
+ `revisions` does not find them; [Reading revisions](#reading-revisions) has a
485
+ snippet that rewrites them. A query that filters `item_type` by a subclass
486
+ name stops matching new rows; filter by the base class, or by the snapshot's
487
+ inheritance column.
488
+ - New revisions record associations as snapshots on `create` and `destroy`
489
+ only, without their `changes`, and `update` revisions carry no
490
+ `associations`. `changed_associations` lists only the associations that hold
491
+ changes, and `association_changeset` returns `nil` where it raised.
492
+ - A `destroy` revision's `changes` hold only the entries from `changes:`, and
493
+ the key is omitted when there are none.
494
+ - Snapshots hold the values last loaded from or saved to the database, so a
495
+ `destroy` revision leaves out an assignment made since.
496
+ - For changes made near midnight, `action_date` before the upgrade is the
497
+ server's date and after it the application's.
498
+
171
499
  ## Known issues
172
500
 
173
- The gem is under active maintenance and these defects are known as of 1.2.3:
174
-
175
- - The per-model options above (`ignore:`, `only:`, `associations:`, `async:`)
176
- are not applied. `Recorder::Tape` asks the record instance for
177
- `recorder_options`, but `Recorder::Observer` defines that method on the class,
178
- so the lookup always falls back to `{}` — every observed model records a full
179
- attribute snapshot, synchronously. Global configuration is unaffected.
180
- - `Recorder.enabled=` does not switch recording off. It writes to
181
- `Recorder.config`, which nothing on the recording path reads — the gates are in
182
- `Recorder.store`, which `Recorder::Manager` drives.
183
- - Collection associations are never recorded. `associations:` handles only
184
- singular associations; a `has_many` reflection is skipped without a warning.
501
+ The gem is under active maintenance and these defects are known:
502
+
503
+ - `recorder_disabled!` reaches only the current fiber, not the whole thread:
504
+ `RequestStore` keeps its state in fiber-local storage. Code that runs in
505
+ another fiber inside the block, such as an `Enumerator#next` body or a task
506
+ under a fiber scheduler, is recorded.
185
507
 
186
508
  ## Development
187
509
 
@@ -33,7 +33,7 @@ module Recorder
33
33
  @previous_version = item.dup
34
34
 
35
35
  changes.each do |key, change|
36
- @previous_version.send("#{key}=", change[0])
36
+ @previous_version.try("#{key}=", change[0]) if pair?(change)
37
37
  end
38
38
 
39
39
  @previous_version
@@ -49,10 +49,16 @@ module Recorder
49
49
  @next_version = item.dup
50
50
 
51
51
  changes.each do |key, change|
52
- @next_version.send("#{key}=", change[1])
52
+ @next_version.try("#{key}=", change[1]) if pair?(change)
53
53
  end
54
54
 
55
55
  @next_version
56
56
  end
57
+
58
+ private
59
+
60
+ def pair?(change)
61
+ change.is_a?(Array) && change.size == 2
62
+ end
57
63
  end
58
64
  end
@@ -6,8 +6,7 @@ module Recorder
6
6
  # Global configuration options
7
7
  class Config
8
8
  include Singleton
9
- attr_accessor :sidekiq_options
10
- attr_reader :ignore, :async
9
+ attr_reader :ignore
11
10
 
12
11
  def initialize
13
12
  reset
@@ -17,10 +16,6 @@ module Recorder
17
16
  @ignore = Array.wrap(value).map(&:to_sym)
18
17
  end
19
18
 
20
- def async=(value)
21
- @async = !!value
22
- end
23
-
24
19
  # Indicates whether Recorder is on or off. Default: true.
25
20
  def enabled
26
21
  @mutex.synchronize { !!@enabled }
@@ -33,15 +28,7 @@ module Recorder
33
28
  def reset
34
29
  @mutex = Mutex.new
35
30
  @enabled = true
36
-
37
- @sidekiq_options = {
38
- queue: 'recorder',
39
- retry: 10,
40
- backtrace: true
41
- }
42
-
43
31
  @ignore = []
44
- @async = false
45
32
  end
46
33
  end
47
34
  end
@@ -2,14 +2,21 @@
2
2
 
3
3
  module Recorder
4
4
  module Manager
5
+ # Without a block, disables recording until `recorder_enabled!`. With one,
6
+ # disables it for the block and then restores the state it found.
5
7
  def recorder_disabled!
8
+ was_enabled = Recorder.store.recorder_enabled?
6
9
  Recorder.store.recorder_disabled!
7
10
  return unless block_given?
8
11
 
9
12
  begin
10
13
  yield
11
14
  ensure
12
- Recorder.store.recorder_enabled!
15
+ if was_enabled
16
+ Recorder.store.recorder_enabled!
17
+ else
18
+ Recorder.store.recorder_disabled!
19
+ end
13
20
  end
14
21
  end
15
22
 
@@ -2,44 +2,72 @@
2
2
 
3
3
  require 'recorder/tape'
4
4
  require 'active_support/concern'
5
+ require 'active_support/core_ext/object/deep_dup'
5
6
 
6
7
  module Recorder
7
8
  module Observer
8
9
  extend ::ActiveSupport::Concern
9
10
 
11
+ # The condition every `recorder` callback checks before the model's own.
12
+ RECORDING = -> { Recorder.recording? }
13
+
10
14
  included do
11
15
  has_many :revisions, class_name: '::Recorder::Revision', inverse_of: :item, as: :item
12
16
  end
13
17
 
14
- def recorder_dirty?
15
- return @recorder_dirty if defined?(@recorder_dirty)
16
-
17
- true
18
- end
19
-
20
- def recorder_record?
21
- recorder_dirty? && Recorder.store.recorder_enabled?
18
+ # A copy of the options passed to `.recorder`, which the caller may change.
19
+ # A model may define this itself to decide them per record, all but `if:`
20
+ # and `unless:`, which the callbacks hold.
21
+ def recorder_options
22
+ self.class.recorder_options.deep_dup
22
23
  end
23
24
 
24
25
  class_methods do
25
- define_method :recorder_options do
26
- @recorder_options ||= {}
26
+ # The options passed to `.recorder` in this class or the nearest ancestor,
27
+ # frozen and with symbol keys.
28
+ def recorder_options
29
+ return @recorder_options if defined?(@recorder_options)
30
+
31
+ superclass.respond_to?(:recorder_options) ? superclass.recorder_options : Recorder::Options::NONE
27
32
  end
28
33
 
34
+ # The class, this one or the nearest ancestor, that called `.recorder`.
35
+ def recorder_declared_in
36
+ return self if instance_variable_defined?(:@recorder_options)
37
+
38
+ superclass.recorder_declared_in if superclass.respond_to?(:recorder_declared_in)
39
+ end
40
+
41
+ # Registers the callbacks, which subclasses inherit, so it is called once
42
+ # per class hierarchy. The callbacks hold `if:` and `unless:`, so the
43
+ # `recorder_options` overrides cannot change them.
29
44
  def recorder(options = {})
30
- @recorder_options = options
45
+ declared_in = [*ancestors, *descendants].find { |klass| klass.instance_variable_defined?(:@recorder_options) }
46
+ if declared_in
47
+ raise ArgumentError, "`recorder` is already declared in #{declared_in.name || declared_in.inspect}. " \
48
+ 'Declare it once per class hierarchy, in the topmost class that records, and define a ' \
49
+ '`recorder_options` instance method where a subclass needs other options. `if:` and `unless:` ' \
50
+ 'stay as declared.'
51
+ end
31
52
 
32
- after_create do
33
- Recorder::Tape.new(self).record_create if recorder_record?
53
+ options = Recorder::Options.normalize(options)
54
+ # Rails checks the conditions in order, so the model's own runs only
55
+ # while recording is on.
56
+ conditions = {if: [RECORDING, options[:if]].compact, unless: options[:unless]}
57
+
58
+ after_create(**conditions) do
59
+ Recorder::Tape.new(self).record_create
34
60
  end
35
61
 
36
- after_update do
37
- Recorder::Tape.new(self).record_update if recorder_record?
62
+ after_update(**conditions) do
63
+ Recorder::Tape.new(self).record_update
38
64
  end
39
65
 
40
- after_destroy do
41
- Recorder::Tape.new(self).record_destroy if recorder_record?
66
+ after_destroy(**conditions) do
67
+ Recorder::Tape.new(self).record_destroy
42
68
  end
69
+
70
+ @recorder_options = options
43
71
  end
44
72
  end
45
73
  end