Project

General

Profile

Actions

Feature #21219

open

`Object#inspect` accept a list of instance variables to display

Added by byroot (Jean Boussier) 8 days ago. Updated 5 days ago.

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

Description

Context

The default Object#inspect implementation is quite useful to have a generic representation of objects in error message and similar places.

However sometimes objects are referencing other objects with a very large inspect representation, making error message hard to understand.

In some other cases, some instance variables are holding secrets such as password or private keys, and the default inspect behavior can cause
these secrets to be leaked in logs among other places.

You can of course define your own inspect implementation for any object, but it's not as simple as it may seems because you need to handle circular references, otherwise you can end up with a SystemStackError.
Also, it's more minor, but since Ruby 2.7, you can no longer access an object's address, so you can't implement an inspect method that is consistent with Object#inspect

From my experience, user defined implementations of #inspect are very rare, and I think the above is in part responsible.

Feature

I think it would be useful if the default Object#inspect implementation accepted a list of instance variables to display, so that you could very easily hide internal state, either because it's too verbose, or because it is secret:

require 'logger'
logger = Logger.new(STDOUT)

class DatabaseConfig
  def initialize(host, user, password)
    @host = host
    @user = user
    @password = password
  end

  def inspect = super(instance_variables: [:@host, :@user])
end


env = {db_config: DatabaseConfig.new("localhost", "root", "hunter2")}
logger.info("something happened, env: #{env}")
INFO -- : something happened, env: {db_config: #<DatabaseConfig:0x00000001002b3a08 @host="localhost", @user="root">}
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0