Skip to content

Instantly share code, notes, and snippets.

@alexshagov
Created May 11, 2020 14:52
Show Gist options
  • Save alexshagov/b5d2b3ef54718161a190fbb900c3f286 to your computer and use it in GitHub Desktop.
Save alexshagov/b5d2b3ef54718161a190fbb900c3f286 to your computer and use it in GitHub Desktop.
Ruby on Rails: database changes logger
# frozen_string_literal: true
### Usage
# Helps to understand how operation run affects the database state
# DatabaseChangesLogger.call(filename: 'output') { Operation.perform }
module DatabaseChangesLogger
EVENTS_TYPE = 'sql.active_record'
OPERATION_REGEX = /Update|Create/.freeze
def self.call(filename: nil)
return unless filename
ActiveSupport::Notifications.subscribed(log_to(filename), EVENTS_TYPE) do
yield
end
end
def self.log_to(filename)
lambda { |*args|
event = ActiveSupport::Notifications::Event.new(*args)
if event.payload[:name]&.match?(OPERATION_REGEX)
filename = Rails.root.join(filename)
File.open(Rails.root.join(filename), mode: 'a') do |f|
f.write "\n"
f.write(event.payload[:name])
f.write "\n"
f.write(event.payload[:sql])
f.write "\n"
f.write("=============================")
f.write "\n"
end
end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment