Class: TrackChanges::Snapshot
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- TrackChanges::Snapshot
- Defined in:
- app/models/track_changes/snapshot.rb
Class Method Summary collapse
- .dump_attribute_value(value) ⇒ Object
-
.record_state(record) ⇒ Object
Returns a hash of the current values for all tracked fields on the record.
Instance Method Summary collapse
- #capture_record_state ⇒ Object
-
#create_diff(diff_attributes = {}) ⇒ Object
Creates a diff object that shows the changes between this snapshot and the record’s state.
-
#update ⇒ Object
Updates the snapshot to the current record state.
Class Method Details
.dump_attribute_value(value) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'app/models/track_changes/snapshot.rb', line 16 def self.dump_attribute_value(value) case value when ActiveRecord::Relation dump_attribute_value(value.to_a).sort when Array value.map {|member| dump_attribute_value(member) } when ActiveRecord::Base value.send(value.class.primary_key) else value end end |
.record_state(record) ⇒ Object
Returns a hash of the current values for all tracked fields on the record
12 13 14 |
# File 'app/models/track_changes/snapshot.rb', line 12 def self.record_state(record) Hash[record.class.track_changes_fields.collect {|method_name| [method_name, dump_attribute_value(record.send(method_name))] }] end |
Instance Method Details
#capture_record_state ⇒ Object
51 52 53 |
# File 'app/models/track_changes/snapshot.rb', line 51 def capture_record_state self.state = self.class.record_state(record) end |
#create_diff(diff_attributes = {}) ⇒ Object
Creates a diff object that shows the changes between this snapshot and the record’s state
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'app/models/track_changes/snapshot.rb', line 30 def create_diff(diff_attributes = {}) record_state = self.class.record_state(record) snapshot_state = self.state from = {} to = {} record.class.track_changes_fields.each do |key| if snapshot_state.key?(key) && snapshot_state[key] != record_state[key] # We check for the existence of the key in the snapshot before recording so we don't declare newly tracked attributes as "changed" on their first time recorded from[key] = snapshot_state[key] to[key] = record_state[key] end end diff_attributes = diff_attributes.reverse_merge(:from => from, :to => to) record.diffs.create!(diff_attributes) unless diff_attributes[:from].empty? && diff_attributes[:to].empty? end |
#update ⇒ Object
Updates the snapshot to the current record state
47 48 49 |
# File 'app/models/track_changes/snapshot.rb', line 47 def update save end |