Created
April 14, 2010 19:50
-
-
Save brentd/366249 to your computer and use it in GitHub Desktop.
Temporarily redirect ActiveRecord query logging
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
# Semi-evil way to force ActiveRecord to temporarily redirect where it's | |
# logging SQL queries. Quick way to find out why the crap that query | |
# isn't working - helpful especially when debugging a failing test. | |
# | |
# Can't use `ActiveRecord::Base.logger = foo` because that'll only work for | |
# new DB connections. Can't just reset connections because doing so in the | |
# middle of a test would abort transactions. | |
# | |
# So we resort to evil... | |
# | |
# Example: | |
# | |
# log_to(STDOUT) { Person.all } #=> "SELECT * FROM people;" | |
# | |
def log_to(stream) | |
old_logger = ActiveRecord::Base.connection.instance_variable_get(:@logger) | |
ActiveRecord::Base.connection.instance_variable_set(:@logger, Logger.new(stream)) | |
yield | |
ActiveRecord::Base.connection.instance_variable_set(:@logger, old_logger) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment