Print-based debugging is all about making your log messages stand out and being easily digestible. Here are some less common but potentially helpful hacks and tips for debugging.
Custom Delimiters: You can create visually distinct delimiters:
puts "="*50
puts "DEBUG START"
puts "="*50
Colorize Output: Using the colorize gem, you can add color to your debug messages to make them pop out:
require 'colorize'
puts "Debugging...".red
Time-Stamped Logs: Add timestamps to your logs to know when each message was printed:
puts "#{Time.now} - #{@user.name}"
Use Vertical Space: Insert multiple newline characters to create a visual break:
puts "\n\n\n"
puts @user.inspect
puts "\n\n\n"
Hierarchy Indicators: If you’re debugging nested loops or recursive functions, you can create a visual hierarchy:
puts "--- Level 1 ---"
puts "------ Level 2 ------"
Custom Debugging Method: Create a custom debug printing method to automate some of the patterns you frequently use:
def custom_debug(message, delimiter="*")
puts delimiter * 30
puts message
puts delimiter * 30
end
Tabulate Data: If you’re printing arrays or collections, presenting them in a tabulated format can be more readable:
@users.each do |user|
puts "| #{user.id} | #{user.name} | #{user.email} |"
end
External Libraries for Formatting: Use libraries like awesome_print to get well-formatted and colorized output:
require 'awesome_print'
ap @user
ActiveRecord Queries: Print the actual SQL query being executed by an ActiveRecord query:
puts User.where(email: 'test@email.com').to_sql
puts @user.attributes.to_s
Dump Object to a File: If the object is too large, dump it into a file to inspect later:
File.open("debug_output.txt", "w") { |f| f.write(Order.all.inspect) }