Created
July 16, 2020 20:39
-
-
Save stympy/642ac76c0716b7e4c5c6cffbecf199b7 to your computer and use it in GitHub Desktop.
Simple change tracking for Rails models. It also works for non-database-backed models with optional change tracking.
This file contains hidden or 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
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
include ActivityLogger | |
end |
This file contains hidden or 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
module ActivityLogger | |
extend ActiveSupport::Concern | |
included do | |
[["create", "created"], ["update", "updated"], ["destroy", "destroyed"]].each do |meth, action| | |
if respond_to?("after_#{meth}") | |
send("after_#{meth}", -> { log_activity(action) }) | |
end | |
end | |
end | |
protected | |
def activity_data | |
respond_to?(:saved_changes) && saved_changes.any? ? {changes: saved_changes.except("created_at", "updated_at")} : {} | |
end | |
def activity_attributes | |
attributes.slice("id", "name") | |
end | |
def log_activity(action, data: nil) | |
data ||= activity_attributes.merge(activity_data) | |
# This assumes Current.user is set in a controller, but it will work without it | |
ActiveSupport::Notifications.instrument("activity", {event: "#{action}-#{model_name.singular}", user_id: Current.user&.id, data: data}) | |
end | |
end |
This file contains hidden or 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
ActiveSupport::Notifications.subscribe("activity") do |*args| | |
event = ActiveSupport::Notifications::Event.new(*args) | |
Rails.logger.info({ activity: event.payload.compact }.to_json) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment