mongo-hacker icon indicating copy to clipboard operation
mongo-hacker copied to clipboard

Output "hook"

Open rogerbinns opened this issue 13 years ago • 4 comments

One of my fields is named "time" and the value is Unix seconds since the epoch (1970). It would be nice if there was a way to automagically output this field showing a human readable time value.

I have another field that has a boolean value. 99% of the time the value is false, and I don't want the field displayed if that is the case as it is just noise.

Perhaps some sort of hook where I can provide a function that is called with a field name and value and it returns what to display (or nothing)? (If you've used emacs you'll know what I mean)

rogerbinns avatar Sep 10 '12 19:09 rogerbinns

Yeah, that would be awesome. Thanks for the idea.

TylerBrock avatar Sep 13 '12 20:09 TylerBrock

Do you want to take a stab at this and issue a pull request?

TylerBrock avatar Feb 03 '13 00:02 TylerBrock

It's ugly but the way I see of doing this is two hooks. The first is called with the original object (this.next()) and can modify it as necessary. The second hook would need to be the line in tojsonObject that prints each key and value and let the hook do that so it can apply its own colouring, conversion, or even key or value omission.

rogerbinns avatar Mar 06 '13 13:03 rogerbinns

The first approach turned out nasty, since you don't really want to alter the object and there are several places objects can come from. Altering the object meant that a numeric timestamp got turned into a string and displayed with string colouring.

The second approach works well but is still somewhat ugly - you won't want to do things exactly this way - I've made a gist with how I am doing things internally as an example.

There is a displayHook function which is passed the object, key, value and current indent etc. If it returns false then the key: value is not displayed, returning true displays as normal and anything else is used as the display. You can see the function at the end. (Keys are also sorted since I don't use ordered objects/dicts.)

https://gist.github.com/rogerbinns/5120508

There should probably be formatKey or similar function to handle keys. tojsonobject is also a bit messy when it comes to commas and newlines. The approach I usually use is keep track of if I've added anything to the output yet. If so then commas and newlines are added before adding the second and subsequent items. This doesn't require tracking the number of items or enumeration counts.

Example before:

"headset": false,
"resolution": [
     1280,
     752],
"time": 1362482406.289,

Example after:

"resolution": 1280 x 752,
"time": 1362482406.289 # Tue Mar  5 03:20:06 2013,

rogerbinns avatar Mar 08 '13 22:03 rogerbinns