Project

General

Profile

Actions

Feature #20987

open

Add dbg - minimal debugging helper

Added by pawurb (Pawel Urbanek) 12 days ago. Updated 11 days ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:120428]

Description

Hi. It's my first time contributing here, so I'm sorry in advance if I've mixed something up.

I’m author of https://github.com/pawurb/dbg-rb gem. dbg method is inspired by Rust where it's built-in into std-lib (https://doc.rust-lang.org/std/macro.dbg.html). AFAIK in Ruby there's no simple mechanism to puts debug values together with caller info without using external dependencies. What’s more frustrating is that while p nil outputs nil to the std, puts nil prints a blank line, sometimes making debugging sessions confusing.

I would like to propose adding a minimal dbg helper method to stdlib:

dbg("Hello world", [1, 2, 3])
# => [dir/file.rb:12] "Hello world"
# => [dir/file.rb:12] [1, 2, 3]

dbg will produce verbose output together with informative file name and LOC info. I think that such built-in feature would be useful for many Ruby devs.

My gem uses external dependencies, but I've came up with this barebones implementation:

def dbg(*msgs)
  loc = caller_locations.first.to_s
  matching_loc = loc.match(/.+(rb)\:\d+\:(in)\s/)
  src = if matching_loc.nil?
      loc
    else
      matching_loc[0][0..-5]
    end
  file, line = src.split(":")
  file = file.split("/").last(2).join("/")
  src = "[#{file}:#{line}]"

  msgs.each do |msg|
    puts "#{src} #{msg.inspect}"
  end
  nil
end

Files

Screenshot 2024-12-27 at 00.00.23.png (81.5 KB) Screenshot 2024-12-27 at 00.00.23.png pawurb (Pawel Urbanek), 12/26/2024 11:28 PM
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0