awesome-print / awesome_print

Pretty print your Ruby objects with style -- in full color and with proper indentation
http://github.com/michaeldv/awesome_print
MIT License
4.07k stars 454 forks source link

Option to hide key/value pairs in hash that are nil? #327

Open drsharp opened 6 years ago

drsharp commented 6 years ago

I'm opening this issue for discussion. I love AP but with some Rails AR objects, there are a LOT of fields that are nil by default. It would be great to have some option to simply ignore the keys with a nil value. This would be particularly useful when viewing AR objects that may only have a subset of attributes with actual values.

I could see two uses here...

Use 1: simply hide them

2.2.5 :001 > foo = { one: 1, two: nil, three: nil }
{
      :one => 1,
      :two => nil,
    :three => nil
}
2.2.5 :002 > ap foo, { hide_nils: true }
{
    :one => 1
}

Use 2: group them at the end as a separate list

2.2.5 :003 > foo = { one: 1, two: nil, three: nil }
{
      :one => 1,
      :two => nil,
    :three => nil
}
2.2.5 :004 > ap foo, { group_nils: true }
{
    :one => 1
}
nils => :two, :three

I know that this is a little sneaky, because it's not showing the full object's attributes, but it would be so very useful when inspecting objects with lots of nil attributes.

Thoughts?

aks commented 5 years ago

Put this into a file, say hash_no_nils.rb

module HashNoNils
  def no_nil_values
    reject { |_k, v| v.nil? }
  end
end
Hash.prepend HashNoNils

then, in the code:

require 'hash_no_nils'

...
2.2.5 :001 > foo = { one: 1, two: nil, three: nil }
{
      :one => 1,
      :two => nil,
    :three => nil
}
2.2.5 :002 > ap foo.no_nil_values
{
    :one => 1
}

all done!

Bizcho commented 2 years ago

I'll take a swing at adding this function. Sunds great for debugin.