Make RoR nested in an array

Using the presented gem , I am looking to nest an object in an array, with that array only having one object. I cannot figure out how to do this. Any ideas? The reason for this has to do with how the Google Tag Manager handles advanced ecommerce tracking.

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

      

Spits out:

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

      

Whenever I want, we exit as:

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

      

+3


source to share


1 answer


You can just use the collection in the representable module. Although you only have one object, since you want to wrap it in an array. It technically becomes a collection with one object. Then define a getter with that collection name in the parent. Here's 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

      

+1


source







All Articles