ruby-on-railsrubyjsonrepresentable

Make RoR nested representable into an array


In using the representable gem, I am looking to nest an object within an array, with that array only having one object. I can't see to figure out how to accomplish this. Any ideas? The reason for this is due to how Google Tag Manager handles enhanced ecommerce tracking.

nested 'products' do
  property :name, getter: lambda{|*| name }
  property :id
end

Will spit out:

"products": {
  "name" : "Nike Swoosh",
  "id" : 8
}

When I want is to come out as:

"products": [ {
  "name" : "Nike Swoosh",
  "id" : 8
} ] 

Solution

  • You can just use the collection in the representable module. Although you have only a single object, since you want to wrap it in an Array. It technically become a collection with a single object. Then define a getter with that collection name in the parent object. Here is an example:

    require 'ostruct'
    require 'representable'
    require 'representable/json'
    
    class Order < Struct.new(:order, :product)
    
       def products
         [product]
       end  
    end
    
    module OrderRepresenter
      include Representable::JSON
    
      property :name
      collection :products
    end
    
    
    sale = Order.new(name: "An order name", product: {name: "My Product", id: 1})
    p sale.extend(SaleRepresenter).to_json