recorder 1.4.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.
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/core_ext/hash/keys'
4
+
5
+ module Recorder
6
+ # Checks the options passed to `.recorder` and stores them as a frozen,
7
+ # symbol-keyed copy.
8
+ # @api private
9
+ module Options
10
+ KEYS = %i[ignore only associations changes if unless].freeze
11
+ ASSOCIATION_KEYS = %i[ignore only].freeze
12
+ # What a class whose hierarchy never called `.recorder` reports.
13
+ NONE = {}.freeze
14
+ # Asynchronous recording was removed in 2.0.0.
15
+ REMOVED_KEYS = %i[async delay].freeze
16
+
17
+ module_function
18
+
19
+ # @raise [ArgumentError] for options that are not a Hash, an unknown key,
20
+ # or an option `Recorder::Tape::Data` or the callbacks cannot apply
21
+ def normalize(options)
22
+ options = symbolize(options, '`recorder`')
23
+ removed = options.keys & REMOVED_KEYS
24
+ if removed.any?
25
+ raise ArgumentError, "`recorder` does not take #{removed.map { |key| "`#{key}:`" }.join(" or ")}: " \
26
+ 'asynchronous recording was removed in 2.0.0, and every revision is written in the save transaction.'
27
+ end
28
+
29
+ assert_known_keys(options, KEYS, '`recorder`')
30
+ Recorder::Tape::Data.validate_changes_option!(options[:changes])
31
+ %i[if unless].each { |key| validate_condition(key, options[key]) }
32
+ options[:associations] = normalize_associations(options[:associations]) if options.key?(:associations)
33
+
34
+ deep_freeze(options)
35
+ end
36
+
37
+ # Rails passes the record to a Proc of arity 1 and nothing to one of arity
38
+ # 0; any other Proc raises from the save.
39
+ def validate_condition(key, condition)
40
+ return if condition.nil? || condition.is_a?(Symbol) || (condition.is_a?(Proc) && [0, 1].include?(condition.arity))
41
+
42
+ raise ArgumentError, "`#{key}:` expects a method name as a Symbol, or a Proc that takes the record or " \
43
+ "nothing, got #{condition.inspect}"
44
+ end
45
+
46
+ # Takes a Hash of association name => options, or an Array of names, and
47
+ # symbolizes the names either way.
48
+ def normalize_associations(associations)
49
+ return if associations.nil?
50
+ return associations.map { |name| association_name(name) } if associations.is_a?(Array)
51
+ unless associations.is_a?(Hash)
52
+ raise ArgumentError, "`associations:` expects a Hash or an Array of names, got #{associations.inspect}"
53
+ end
54
+
55
+ associations.each_with_object({}) do |(name, options), normalized|
56
+ name = association_name(name)
57
+ raise ArgumentError, "`associations:` names `#{name}` both as a Symbol and as a String" if normalized.key?(name)
58
+
59
+ normalized[name] = association_options(name, options)
60
+ end
61
+ end
62
+
63
+ def association_name(name)
64
+ return name.to_sym if name.is_a?(Symbol) || name.is_a?(String)
65
+
66
+ raise ArgumentError, "`associations:` expects association names as Symbols or Strings, got #{name.inspect}"
67
+ end
68
+
69
+ def association_options(name, options)
70
+ return if options.nil?
71
+
72
+ owner = "`associations[#{name.inspect}]`"
73
+ options = symbolize(options, owner)
74
+ assert_known_keys(options, ASSOCIATION_KEYS, owner)
75
+ options
76
+ end
77
+
78
+ def assert_known_keys(options, keys, owner)
79
+ unknown = options.keys - keys
80
+ return if unknown.empty?
81
+
82
+ raise ArgumentError, "Unknown key#{"s" if unknown.many?}: #{unknown.map(&:inspect).join(", ")} in #{owner}. " \
83
+ "Valid keys are: #{keys.map(&:inspect).join(", ")}"
84
+ end
85
+
86
+ def symbolize(options, owner)
87
+ raise ArgumentError, "#{owner} expects a Hash of options, got #{options.inspect}" unless options.is_a?(Hash)
88
+
89
+ options.each_with_object({}) do |(key, value), symbolized|
90
+ unless key.is_a?(Symbol) || key.is_a?(String)
91
+ raise ArgumentError, "#{owner} expects option names as Symbols or Strings, got #{key.inspect}"
92
+ end
93
+ raise ArgumentError, "#{owner} got `#{key}` both as a Symbol and as a String" if symbolized.key?(key.to_sym)
94
+
95
+ symbolized[key.to_sym] = value
96
+ end
97
+ end
98
+
99
+ # Copies hashes, arrays and strings, so freezing them leaves the caller's
100
+ # own objects alone. A Proc is kept as it is, unfrozen.
101
+ def deep_freeze(value)
102
+ case value
103
+ when Hash then value.to_h { |key, item| [key, deep_freeze(item)] }.freeze
104
+ when Array then value.map { |item| deep_freeze(item) }.freeze
105
+ when String then value.dup.freeze
106
+ else value
107
+ end
108
+ end
109
+ end
110
+ end
@@ -6,18 +6,6 @@ module Recorder
6
6
  class Revision < ActiveRecord::Base
7
7
  self.table_name = 'recorder_revisions'
8
8
 
9
- if ::Recorder.active_record_protected_attributes?
10
- attr_accessible(
11
- :event,
12
- :user_id,
13
- :ip,
14
- :user_agent,
15
- :action_date,
16
- :data,
17
- :meta
18
- )
19
- end
20
-
21
9
  belongs_to :item, polymorphic: true, inverse_of: :revisions, optional: true
22
10
  belongs_to :user, optional: true
23
11
 
@@ -26,22 +14,9 @@ module Recorder
26
14
  validates :action_date, presence: true
27
15
  validates :data, presence: true
28
16
 
29
- scope :ordered_by_created_at, -> { order(created_at: :desc) }
30
-
31
- # def item
32
- # return @item if defined?(@item)
33
- # return if item_id.nil?
34
-
35
- # @item = item_type.classify.constantize.new(data['attributes'])
36
-
37
- # if data['associations'].present?
38
- # data['associations'].each do |name, association|
39
- # @item.send("build_#{name}", association['attributes'])
40
- # end
41
- # end
42
-
43
- # @item
44
- # end
17
+ # Newest first. Revisions written in the same instant fall back to the
18
+ # order they were inserted in.
19
+ scope :ordered_by_created_at, -> { order(created_at: :desc, id: :desc) }
45
20
 
46
21
  # Get changeset for an item
47
22
  # @return [Recorder::Changeset]
@@ -53,24 +28,39 @@ module Recorder
53
28
  @item_changeset ||= changeset_class(item).new(item, data['changes'])
54
29
  end
55
30
 
56
- # Get names of item associations that has been changed
31
+ # Get names of item associations that carry changes
57
32
  # @return [Array]
58
33
  def changed_associations
59
- data['associations'].try(:keys) || []
34
+ recorded_associations.select { |_name, entry| association_changes(entry) }.keys
60
35
  end
61
36
 
62
37
  # Get changeset for an association
63
38
  # @param name [String] name of association to return changeset
64
- # @return [Recorder::Changeset]
39
+ # @return [Recorder::Changeset, nil] nil when the revision holds no changes for it
65
40
  def association_changeset(name)
41
+ return nil if item.nil?
42
+
43
+ changes = association_changes(recorded_associations[name.to_s])
44
+ return nil if changes.nil?
45
+
66
46
  association = item.send(name)
67
- # association = association.source if association.decorated?
47
+ return nil if association.nil?
68
48
 
69
- changeset_class(association).new(association, data['associations'].fetch(name.to_s).try(:fetch, 'changes'))
49
+ changeset_class(association).new(association, changes)
70
50
  end
71
51
 
72
52
  protected
73
53
 
54
+ # @api private
55
+ def recorded_associations
56
+ data['associations'].is_a?(Hash) ? data['associations'] : {}
57
+ end
58
+
59
+ # @api private
60
+ def association_changes(entry)
61
+ entry['changes'].presence if entry.is_a?(Hash)
62
+ end
63
+
74
64
  # Returns changeset class for passed object.
75
65
  # Changeset class name can be overriden with `#recorder_changeset_class` method.
76
66
  # If `#recorder_changeset_class` method is not defined, then class name is generated as "#{class}Changeset"
@@ -92,4 +82,8 @@ module Recorder
92
82
  klass.present? ? klass : Recorder::Changeset
93
83
  end
94
84
  end
85
+
86
+ # Raised from the save of an observed record when its revision fails
87
+ # validation or a callback halts it. `record` is the revision.
88
+ class RevisionNotSaved < ActiveRecord::RecordNotSaved; end
95
89
  end
@@ -20,10 +20,6 @@ module Recorder
20
20
  store[:enabled]
21
21
  end
22
22
 
23
- def recorder_disabled?
24
- !store[:enabled]
25
- end
26
-
27
23
  private
28
24
 
29
25
  def store
@@ -1,8 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'concurrent/map'
4
+
3
5
  module Recorder
4
6
  class Tape
5
7
  class Data
8
+ # The `associations:` warnings already logged, by class name and message.
9
+ WARNED = Concurrent::Map.new
10
+
6
11
  attr_reader :item
7
12
 
8
13
  def initialize(item)
@@ -20,7 +25,7 @@ module Recorder
20
25
  end
21
26
 
22
27
  def attributes_for(_event, options)
23
- {attributes: sanitize_attributes(item.attributes, options)}
28
+ {attributes: sanitize_attributes(persisted_attributes, options)}
24
29
  end
25
30
 
26
31
  def self.validate_changes_option!(callback)
@@ -30,12 +35,14 @@ module Recorder
30
35
  end
31
36
 
32
37
  def changes_for(event, options)
33
- changes = sanitize_attributes(item.saved_changes, options).merge(custom_changes_for(event, options))
38
+ changes = attribute_changes_for(event, options).merge(custom_changes_for(event, options))
34
39
 
35
40
  changes.present? ? {changes: changes} : {}
36
41
  end
37
42
 
38
43
  def associations_for(event, options)
44
+ return {} if event.to_sym == :update
45
+
39
46
  associations = parse_associations_attributes(event, options)
40
47
 
41
48
  associations.present? ? {associations: associations} : {}
@@ -43,6 +50,21 @@ module Recorder
43
50
 
44
51
  private
45
52
 
53
+ # The values the record last loaded or saved; one that was never saved
54
+ # has only its in-memory values.
55
+ def persisted_attributes
56
+ return item.attributes if item.new_record?
57
+
58
+ item.attributes.merge(item.attributes_in_database)
59
+ end
60
+
61
+ # `destroy` leaves `saved_changes` holding the record's last save.
62
+ def attribute_changes_for(event, options)
63
+ return {} if event.to_sym == :destroy
64
+
65
+ sanitize_attributes(item.saved_changes, options)
66
+ end
67
+
46
68
  def custom_changes_for(event, options)
47
69
  callback = options[:changes]
48
70
  return {} unless callback
@@ -76,32 +98,51 @@ module Recorder
76
98
  options[:associations].each_with_object({}) do |(association, options), hash|
77
99
  name, data = parse_association(event, association, options)
78
100
 
79
- hash[name] = data if data&.any?
101
+ hash[name] = data if data
80
102
  end
81
103
  end
82
104
 
105
+ # Logs a warning for a collection, and for a name that no class in the
106
+ # item's hierarchy declares, and skips both.
83
107
  def parse_association(event, association, options)
84
108
  reflection = item.class.reflect_on_association(association)
85
109
 
86
- if reflection.present?
87
- if reflection.collection?
88
-
89
- elsif (object = item.send(association))
90
- data = Recorder::Tape::Data.new(object).data_for(event, options || {})
91
-
92
- [reflection.name, data]
110
+ if reflection.nil?
111
+ unless association_in_hierarchy?(association)
112
+ warn_unrecordable("names #{association.inspect}, which is not an association of #{item.class}")
93
113
  end
114
+ elsif reflection.collection?
115
+ warn_unrecordable("names the collection #{association.inspect} of #{item.class}; " \
116
+ 'only singular associations are recorded')
117
+ elsif (object = item.send(association)) && !unsaved_on_destroy?(object, event)
118
+ [reflection.name, Recorder::Tape::Data.new(object).attributes_for(event, options || {})]
94
119
  end
95
120
  end
96
121
 
97
- def record_changed?(data, event)
98
- event.to_sym != :update || data[:changes] || associations_changed?(data)
122
+ # A record that was never saved has no row for a destroy to describe; on
123
+ # create, Rails saves it in the same transaction.
124
+ def unsaved_on_destroy?(object, event)
125
+ event.to_sym == :destroy && object.new_record?
99
126
  end
100
127
 
101
- def associations_changed?(data)
102
- return if data[:associations].nil?
128
+ # Subclasses inherit `associations:`, so an entry can name an association
129
+ # that only a sibling declares.
130
+ def association_in_hierarchy?(association)
131
+ declared_in = item.class.recorder_declared_in || item.class
132
+
133
+ [declared_in, *declared_in.descendants].any? { |klass| klass.reflect_on_association(association) }
134
+ end
103
135
 
104
- data[:associations].any? { |name, association| association[:changes] }
136
+ # Once per class and message in a process.
137
+ def warn_unrecordable(message)
138
+ return unless WARNED.put_if_absent([item.class.name, message], true).nil?
139
+
140
+ item.class.logger&.warn("Recorder: `associations:` #{message}")
141
+ nil
142
+ end
143
+
144
+ def record_changed?(data, event)
145
+ event.to_sym != :update || data[:changes]
105
146
  end
106
147
  end
107
148
  end
@@ -3,41 +3,30 @@
3
3
  module Recorder
4
4
  class Tape
5
5
  module Record
6
- def record(params, options = {})
7
- return if Recorder.store.recorder_disabled?
8
-
9
- params = params_for(params)
10
-
11
- if async?(options)
12
- record_async(params, options)
13
- else
14
- Recorder::Revision.create(params)
15
- end
6
+ def record(params)
7
+ return unless Recorder.recording?
8
+
9
+ revision = Recorder::Revision.new(params_for(params))
10
+ revision.save!
11
+ # The failure of a revision written from a callback on this one comes
12
+ # through as it is.
13
+ rescue Recorder::RevisionNotSaved
14
+ raise
15
+ # Re-raised as an error Active Record's save does not rescue, so the save
16
+ # fails, whichever method it was made with. The error names this revision
17
+ # even when a callback on it raised about another record.
18
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved => e
19
+ raise Recorder::RevisionNotSaved.new("Recorder could not write the revision: #{e.message}", revision)
16
20
  end
17
21
 
18
22
  private
19
23
 
24
+ # A revision is dated by the request that made the change, or else today
25
+ # in the application's time zone.
20
26
  def params_for(params)
21
- Recorder.store.params.merge({
22
- action_date: Date.today,
23
- **params
24
- })
25
- end
26
-
27
- def async?(options)
28
- options[:async].nil? ? Recorder.config.async : options[:async]
29
- end
30
-
31
- # Sidekiq accepts only JSON-native job arguments. `data` is serialised
32
- # ahead of the round trip so it survives as a string for the worker to
33
- # parse back; everything else is normalised by the round trip itself.
34
- def record_async(params, options)
35
- params[:data] = params[:data].to_json
36
-
37
- Recorder::Sidekiq::RevisionsWorker.perform_in(
38
- options[:delay] || 2.seconds,
39
- JSON.parse(params.to_json)
40
- )
27
+ Recorder.store.params.merge(params).tap do |merged|
28
+ merged[:action_date] = merged[:action_date].presence || Date.current
29
+ end
41
30
  end
42
31
  end
43
32
  end
data/lib/recorder/tape.rb CHANGED
@@ -4,6 +4,8 @@ require 'recorder/tape/data'
4
4
  require 'recorder/tape/record'
5
5
 
6
6
  module Recorder
7
+ # Writes a record's revisions. Called directly, it skips the model's `if:`
8
+ # and `unless:`, and still honours `Recorder.recording?`.
7
9
  class Tape
8
10
  extend Record
9
11
 
@@ -12,16 +14,13 @@ module Recorder
12
14
  def initialize(item)
13
15
  @item = item
14
16
  @data = Data.new(item)
15
-
16
- item.instance_variable_set(:@recorder_dirty, true)
17
17
  end
18
18
 
19
19
  def record_create
20
- data = data_for(:create, recorder_options)
21
-
22
- record(event: 'create', data: data) if data.any?
20
+ record(event: 'create', data: data_for(:create, recorder_options))
23
21
  end
24
22
 
23
+ # An update that changed nothing has no data and writes no revision.
25
24
  def record_update
26
25
  data = data_for(:update, recorder_options)
27
26
 
@@ -29,15 +28,13 @@ module Recorder
29
28
  end
30
29
 
31
30
  def record_destroy
32
- data = data_for(:destroy, recorder_options)
33
-
34
- record(event: 'destroy', data: data) if data.any?
31
+ record(event: 'destroy', data: data_for(:destroy, recorder_options))
35
32
  end
36
33
 
37
34
  protected
38
35
 
39
36
  def recorder_options
40
- item.respond_to?(:recorder_options) ? item.recorder_options : {}
37
+ item.respond_to?(:recorder_options, true) ? item.send(:recorder_options) : {}
41
38
  end
42
39
 
43
40
  def data_for(event, options)
@@ -46,12 +43,11 @@ module Recorder
46
43
 
47
44
  def record(params)
48
45
  Recorder::Tape.record(
49
- {
50
- item_type: item.class.to_s,
51
- item_id: item.id,
52
- **params
53
- },
54
- recorder_options
46
+ # The value `has_many :revisions` looks rows up by: the base class
47
+ # of an STI subclass.
48
+ item_type: item.class.polymorphic_name,
49
+ item_id: item.id,
50
+ **params
55
51
  )
56
52
  end
57
53
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Recorder
4
- VERSION = '1.4.0'
4
+ VERSION = '2.0.0'
5
5
  end
data/lib/recorder.rb CHANGED
@@ -6,29 +6,54 @@ require 'recorder/version'
6
6
  require 'recorder/changeset'
7
7
  require 'recorder/store'
8
8
  require 'recorder/manager'
9
+ require 'recorder/options'
9
10
  require 'recorder/observer'
10
11
 
11
12
  require 'recorder/rails/controller_concern'
12
- require 'recorder/rails/railtie' if defined? ::Rails::Railtie
13
13
 
14
14
  module Recorder
15
+ # Columns Recorder writes itself, which `Recorder.info` cannot set.
16
+ RESERVED_INFO_KEYS = %i[id item_type item_id event data created_at].freeze
17
+ private_constant :RESERVED_INFO_KEYS
18
+
15
19
  class << self
16
- # Switches Recorder on or off.
20
+ # Switches Recorder on or off for the whole process, every thread
21
+ # included. To switch it off for the current request or thread only, use
22
+ # `Recorder::Manager#recorder_disabled!`.
17
23
  # @api public
18
24
  def enabled=(value)
19
25
  Recorder.config.enabled = value
20
26
  end
21
27
 
22
- # Returns `true` if Recorder is on, `false` otherwise.
23
- # Recorder is enabled by default.
28
+ # Returns `true` if Recorder is on for the process, `false` otherwise.
29
+ # Recorder is enabled by default. `recorder_disabled!` can still have
30
+ # recording off for the current request or thread.
24
31
  # @api public
25
32
  def enabled?
26
33
  !!Recorder.config.enabled
27
34
  end
28
35
 
29
- # Sets Recorder information from the controller.
36
+ # Returns `true` if a change is recorded now: Recorder is on for the
37
+ # process and not switched off for the current request or thread.
38
+ # @api private
39
+ def recording?
40
+ enabled? && store.recorder_enabled?
41
+ end
42
+
43
+ # Sets Recorder information from the controller. Keys are stored as
44
+ # symbols, so a string key replaces the symbol one rather than sitting
45
+ # beside it.
46
+ # @raise [ArgumentError] if the hash sets a column Recorder writes itself
30
47
  # @api public
31
48
  def info=(hash)
49
+ hash = hash.symbolize_keys
50
+ reserved = hash.keys & RESERVED_INFO_KEYS
51
+
52
+ if reserved.any?
53
+ raise ArgumentError, "Recorder.info cannot set columns Recorder writes itself: #{reserved.join(", ")}. " \
54
+ 'To date a revision, set action_date.'
55
+ end
56
+
32
57
  store.params.merge!(hash)
33
58
  end
34
59
 
@@ -38,12 +63,6 @@ module Recorder
38
63
  store.params[:meta] = hash
39
64
  end
40
65
 
41
- # Returns a boolean indicating whether "protected attibutes" should be
42
- # configured, e.g. attr_accessible.
43
- def active_record_protected_attributes?
44
- @active_record_protected_attributes ||= !!defined?(ProtectedAttributes)
45
- end
46
-
47
66
  # Returns Recorder's configuration object.
48
67
  # @api private
49
68
  def config
@@ -65,8 +84,4 @@ module Recorder
65
84
  end
66
85
  end
67
86
 
68
- # if defined?(Sidekiq)
69
- # require 'recorder/sidekiq/revisions_worker'
70
- # end
71
-
72
87
  require 'recorder/revision'
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: recorder
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.4.0
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Igor Alexandrov
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-09-22 00:00:00.000000000 Z
11
+ date: 2026-11-17 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activerecord
@@ -162,6 +162,20 @@ dependencies:
162
162
  - - ">="
163
163
  - !ruby/object:Gem::Version
164
164
  version: '5.0'
165
+ - !ruby/object:Gem::Dependency
166
+ name: simplecov
167
+ requirement: !ruby/object:Gem::Requirement
168
+ requirements:
169
+ - - ">="
170
+ - !ruby/object:Gem::Version
171
+ version: '0.22'
172
+ type: :development
173
+ prerelease: false
174
+ version_requirements: !ruby/object:Gem::Requirement
175
+ requirements:
176
+ - - ">="
177
+ - !ruby/object:Gem::Version
178
+ version: '0.22'
165
179
  description: Recorder tracks changes of your Rails models
166
180
  email:
167
181
  - igor.alexandrov@jetrockets.com
@@ -181,10 +195,9 @@ files:
181
195
  - lib/recorder/config.rb
182
196
  - lib/recorder/manager.rb
183
197
  - lib/recorder/observer.rb
198
+ - lib/recorder/options.rb
184
199
  - lib/recorder/rails/controller_concern.rb
185
- - lib/recorder/rails/railtie.rb
186
200
  - lib/recorder/revision.rb
187
- - lib/recorder/sidekiq/revisions_worker.rb
188
201
  - lib/recorder/store.rb
189
202
  - lib/recorder/tape.rb
190
203
  - lib/recorder/tape/data.rb
@@ -1,11 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Recorder
4
- module Rails
5
- class Railtie < ::Rails::Railtie
6
- initializer 'recorder.configure' do |_app|
7
- require 'recorder/sidekiq/revisions_worker' if defined?(Sidekiq)
8
- end
9
- end
10
- end
11
- end
@@ -1,16 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Recorder
4
- module Sidekiq
5
- class RevisionsWorker
6
- include ::Sidekiq::Worker
7
-
8
- sidekiq_options Recorder.config.sidekiq_options
9
-
10
- def perform(params)
11
- params['data'] = JSON.parse(params['data'])
12
- Recorder::Revision.create(params)
13
- end
14
- end
15
- end
16
- end