Created
May 11, 2020 14:52
-
-
Save alexshagov/b5d2b3ef54718161a190fbb900c3f286 to your computer and use it in GitHub Desktop.
Ruby on Rails: database changes logger
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
# 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