Display array of objects as a table

131 Views Asked by At

I have an array of Candle objects as shown below:

enter image description here

Is there a way in Pharo to display the array in a tabular format?

|       date | open | high | low | close |
|------------+------+------+-----+-------|
| 2018-12-28 |   10 |   20 |  30 |    40 |
| 2019-12-28 |   50 |   60 |  70 |    80 |

gtoolkit

The gtoolkit tour has a slide that seems to mention this:

enter image description here

However, it seems that I'd have to define a special collection for holding Candle objects and then define a gtViewCandlesOn method on it to customize how the candles will be rendered.

Just wondering if there's an approach that will work with normal arrays or if the gtoolkit approach is the way to go.

2

There are 2 best solutions below

0
On

To extend the inspector please check

inspectorPresentationOrder:title:

For example:

AbstractFileReference >> #inspectionContents
    <inspectorPresentationOrder: 0 title: 'Contents'> 
    | maxBytes buffer atEnd stringContents displayStream displayString |
    
    maxBytes := 10000.
    
    self binaryReadStreamDo: [ :stream | 
        buffer := stream next: maxBytes.
        atEnd := stream atEnd ].
    ...
    ^ SpCodePresenter new
        withoutSyntaxHighlight;
        text: displayString;
        whenSubmitDo: [ :text | 
            self writeStreamDo: [ :s | s nextPutAll: text string ] ];
        yourself

But to activate this inspector tab we have this method:

AbstractFileReference >> #inspectionContentsContext: aContext 
    
    aContext active: self isFile

I order to do that in your project you can add some extension methods for the inspector in Array class and print what ever you want when you have an special object in your array.

1
On

It depends on context of use. You can use GToolkit, if you use it on other activities as well. GToolkit is whole framework and probably it is quite overkill to use it just for this tabular view.

Anyway, I did something similar for Pharo launcher command line interface - calling it ConsoleListFormatter. It is pretty straightforward to use, you need to define 2 methods on your candle class (#listPrintAttributeBlocks: #listPrintAttributeLabels:) and set collection of Candles to formatter instance. Calling printList will do the job.

You can use it here ConsoleListFormatter class

Furthermore, if you want to print as collection in the inspector, you would need to override original implementation of #printOn: (or gtViewCandlesOn: in case of use GToolkit inspector) method on Collection class. Rather I would define model class, e.g. CandleList that would use instance var with collection of candles, then you can define your own #printOn: on CandleList without interfering original collection implementation.

Let me know, if you need more details!

Cheers, David