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

Provide a way of specifying custom formatting on user-created classes/objects #420

Open sam0x17 opened 2 years ago

sam0x17 commented 2 years ago

I have a few situations where awesome_print creates a very overly verbose output for some fields on some of my objects, where I would prefer to just be able to specify what awesome_print (and awesome_print alone) sees when it stringifies my objects. Would be amazing if we had some sort of helper where we could annotate objects with hints that tell awesome_print "hey for field :my_field, use this method instead for the stringified version".

senhalil commented 2 years ago

Similar situation here. @sam0x17 we had a similar issue with to_json and the way we handled it was "marking" the fields as :id_only, :none (or by default full object) that way we managed to have "minimal" serialised objects that can be re-created.

However, even if we already have custom :to_s, :inspect and :as_json methods when we call ap on the object, it by-passes these custom functions but if I do ap myObject.inspect or ap myObject.as_json, everything works as expected -- i.e., only the "selected" fields are shown on the screen.

What serialiser ap uses by default? Is there a way to set the object serializer in ap?

senhalil commented 2 years ago

Overloading the :to_hash as well did the trick!

@sam0x17 in case it might be of help to you, we define an option :as_json for the members of a class -- for example each route has a vehicle but we do not want to dump nor display the details of the vehicle object inside route dump so we mark it as as_json: :id here and we override the :as_json as such so that it can dump full object, just id, or nothing at all.