Last active
October 20, 2023 13:54
-
-
Save ximus/ff2ba415defaa83e2f007a2b3c9b83df to your computer and use it in GitHub Desktop.
5min illustration of cheap and dirty change tracking with activerecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# WARN: this relies on the single threaded nature of our apps! | |
class ApplicationModel < ActiveRecord::Base | |
before_save do | |
if ChangeTracking.currently_change_tracking? | |
changeset << [:update, self, changes] | |
end | |
end | |
before_create do | |
if ChangeTracking.currently_change_tracking? | |
changeset << [:create, self, changes] | |
end | |
end | |
before_destroy do | |
... | |
end | |
# ... any other hooks/overrides to catch db changes, like .update_all() | |
end | |
class Loan < ApplicationModel | |
end | |
class AllOtherModelsInAppEtc... < ApplicationModel | |
end | |
module ChangeTracking | |
attr_reader :current_change_tracking_session | |
def with_dry_run | |
# thread safety no-no but ok in our world | |
self.current_change_tracking_session = {} | |
ActiveRecord::Base.transaction do | |
yield | |
raise ActiveRecord::Rollback | |
end | |
current_change_tracking_session | |
ensure | |
self.current_change_tracking_session = nil | |
end | |
def currently_change_tracking? | |
current_change_tracking_session.present? | |
end | |
end | |
# Usage: | |
changes = ChangeTracking.with_dry_run do | |
# call commands | |
# do stuff | |
# do more stuff | |
# whatever | |
end | |
puts "the following changed:" | |
ap changes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment