I'm trying to understand how to use the Jbuilder methods inline in a class. I want to force an object into an array of length one to match the expected JSON spec.
Here is an example of the results I want (note the [] wrapping the value associated with sets):
{
"sets": [{
"set_type": "default_set_type",
"items": [
{
"item_id": "FFFF-0000-111",
"quantity": "1"
}
]
}]
}
Here is my method so far:
def to_3pl
@shipment = self
...
Jbuilder.new do |shipment|
# How do I force jbuilder to wrap a single set with []?
shipment.sets do
shipment.set_type 'default_set_type'
shipment.items @shipment.product_options do |product|
shipment.item_id product.product_id.to_s
shipment.quantity product.quantity.to_s
end
end
end
end
And here is the JSON produced by my method (note that the value associated with sets is not wrapped with []):
{
"sets": {
"set_type": "default_set_type",
"items": [
{
"item_id": "FFFF-0000-111",
"quantity": "1"
}
]
}
}
I've looked through the Jbuilder docs, and am sure there's a way to do this, but I can't seem to figure it out. What is the syntax to force Jbuilder to wrap a single element with [] in a class method?
EDIT WITH SOLUTION
Many thanks to @dddd1919. Here's an updated method with the array wrapper successfully implemented:
def to_3pl
@shipment = self
...
Jbuilder.new do |shipment|
# Forces jbuilder to wrap the object with []
shipment.sets Jbuilder.new.array!(['']) do |set|
shipment.set_type 'default_set_type'
shipment.items @shipment.product_options do |product|
shipment.item_id product.product_id.to_s
shipment.quantity product.quantity.to_s
end
end
end
end