Search code examples
ruby-on-railssavon

Rails - unexpected =>, expecting keyword_end - Savon


I am trying to passing the data below into Savon to send as an XML.

Works perfectly fine when passing one item in.

When I add an each statement for when multiple items are added the following error is created:

syntax error, unexpected =>, expecting keyword_end
  'SalesOrder' => [

Code that does work:

new_or = {

"Order" => {
  "AccountCode" => '#{current_user.accode}',
  "Properties" => {
    "PropertyItem" => [
      {
        "Name" => "Foo",
        "Value" => "Bar",
      },
      {
        "Name" => "Colour",
        "Value" => "Green",
      }
    ]
  }
  "Items" => { 
    'SalesOrder' => {
       'sku' => "SKU-100",
        'Quantity' => 10,
        'Price' => 10.78,
     }
}

} #Close_Order

} #Close new_or

Code that doesn't work:

new_or = {

"Order" => {
  "AccountCode" => '#{current_user.accode}',
  "Properties" => {
    "PropertyItem" => [
      {
        "Name" => "Foo",
        "Value" => "Bar",
      },
      {
        "Name" => "Colour",
        "Value" => "Green",
      }
    ]
  }
  "Items" => { 
    @order.items.each do |item|
       'SalesOrder' => [
        {
          'sku' => item.sku,
          'Quantity' => item.qtny,
          'Price' => item.price,
        },
      ],
  end
}

} #Close_Order

} #Close new_or

Solution

  • First thing I would point out is that you should use map instead of each in this scenario because otherwise it will not return the captured structure of the block, only the original Item records.

    Second, there are quite a lot of syntax issues in your statements, some probably typos in the question since you say that the first section is working, even though there are some issues there as well. But study the following which I assume is the result you are after.

    "Items" => @order.items.map { |item|
        {
            'SalesOrder' => {
                'sku' => item.sku,
                'Quantity' => item.qtny,
                'Price' => item.price
            }
        }
    }
    

    That will result in the following example

    "Items" => [
        {
            'SalesOrder' => {
                'sku' => 10,
                'Quantity' => 100,
                'Price' => 999
            }
        },
        {
            'SalesOrder' => {
                'sku' => 20,
                'Quantity' => 200,
                'Price' => 1299
            }
        }
    ]