将RoR嵌套表示转换成数组

3

在使用 representable gem 时,我想将一个对象嵌套在一个数组中,而该数组只有一个对象。我无法弄清如何实现这一点。有什么想法吗?原因是由于 Google Tag Manager 如何处理增强型电子商务跟踪。

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

将输出:

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

当我想要的是这样表达:

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

我没有使用过这个 gem,但在文档中他们已经解释了关于集合的内容。你可能想要尝试一下。 - Datt
谢谢Datt,但是问题中涉及的对象并不是一个集合,而只是一个单独的对象,因此没有什么可以迭代的。基本上,我只想将该对象放入一个数组中,使其成为一个包含一个索引的数组。 - Du3
1个回答

1
您可以使用 representable 模块中的集合。尽管您只有一个对象,但由于您想将其包装在数组中,因此它在技术上成为具有单个对象的集合。然后在父对象中定义一个以该集合名称为名称的 getter。以下是示例:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接