representable icon indicating copy to clipboard operation
representable copied to clipboard

Representing heterogenous array objects?

Open mlartz opened this issue 11 years ago • 3 comments

Is it possible to represent an object as a heterogeneous, index-based, JSON array, instead of a JSON object (hash)?

So instead of the following:

{ "name": "Album Name", "num_tracks": 10, "isbn": "ISBN", "etc": "etc" }

I'd like to use the following:

["Album Name", 10, "ISBN", "etc"]

I've had good luck using a :reader with the right index, however the :writer is passed a JSON object ({}) instead of an array ([]), so my output JSON looks more like:

{ "0": "Album Name", "1": 10, "2": "ISBN", "3": "etc" }

Is this supported?

mlartz avatar Jul 16 '14 18:07 mlartz

Hi Michael,

cool avatar :) it's not supported out-of-the-box. However, just anything can be achieved with representable :wine_glass:

This is a very special representation - the consumer needs to have knowledge about position and semantic of every item. The order matters here, right?

If I had to do that now, I'd have an intermediate object that transforms my data model into an array and back... Is that array the document itself, or is that a nested property? Damn, I wanted to chill out tonight now you made me think how to implement that......

apotonick avatar Jul 17 '14 09:07 apotonick

Ah, here's a first draft :grin:

module BookRepresenter
  include Representable::Hash

  property :name
  property :isbn

  def to_hash(*)
    hash = super
    array = []
    array << hash["name"]
    array << hash["isbn"]
    array
  end
end

This is only one way but gives you an idea. I'm not really sure how I'd support that from representable......... maybe I need to know the answers to the questions above first.

Now, time to chill. :beer:

apotonick avatar Jul 17 '14 09:07 apotonick

BTW, congratulations for opening issue #100 on representable! :fireworks:

apotonick avatar Jul 17 '14 09:07 apotonick