lutaml / shale

Shale is a Ruby object mapper and serializer for JSON, YAML, TOML, CSV and XML. It allows you to parse JSON, YAML, TOML, CSV and XML data and convert it into Ruby data structures, as well as serialize data structures into JSON, YAML, TOML, CSV or XML.
https://shalerb.org/
MIT License
0 stars 1 forks source link

When a collection is empty, don't render anything #5

Open ronaldtse opened 3 months ago

ronaldtse commented 3 months ago

When a collection is empty, there is no need to render.

Instead, apply render_nil: true behavior when specified. Right now render_nil only works on elements not on collections.

HassanAkbar commented 2 months ago

@ronaldtse I tried to run the below code and it does not render anything if the collection is empty.

require 'shale'
require 'shale/adapter/nokogiri'
Shale.xml_adapter = Shale::Adapter::Nokogiri

class Address < Shale::Mapper
  attribute :city, Shale::Type::String
  attribute :street, Shale::Type::String
  attribute :zip, Shale::Type::String, collection: true

  xml do
    root "address"

    map_element "city", to: :city
    map_element "street", to: :street
    map_element "zip", to: :zip
  end
end

address = Address.from_xml(<<~DATA)
  <address>
    <city>London</city>
    <street>Oxford Street</street>
  </address>
DATA

puts address.to_xml(pretty: true)

the above code outputs the following XML

<address>
  <city>London</city>
  <street>Oxford Street</street>
</address>

Do you mean something else here?