Module: Sequel::Plugins::XmlSerializer

Defined in:
lib/sequel/plugins/xml_serializer.rb

Overview

The xml_serializer plugin handles serializing entire Sequel::Model objects to XML, and deserializing XML into a single Sequel::Model object or an array of Sequel::Model objects. It requires the nokogiri library.

Basic Example:

album = Album[1]
puts album.to_xml
# Output:
# <?xml version="1.0"?>
# <album>
#   <id>1</id>
#   <name>RF</name>
#   <artist_id>2</artist_id>
# </album>

You can provide options to control the XML output:

puts album.to_xml(:only=>:name)
puts album.to_xml(:except=>[:id, :artist_id])
# Output:
# <?xml version="1.0"?>
# <album>
#   <name>RF</name>
# </album>

album.to_xml(:include=>:artist)
# Output:
# <?xml version="1.0"?>
# <album>
#   <id>1</id>
#   <name>RF</name>
#   <artist_id>2</artist_id>
#   <artist>
#     <id>2</id>
#     <name>YJM</name>
#   </artist>
# </album>

You can use a hash value with :include to pass options to associations:

album.to_xml(:include=>{:artist=>{:only=>:name}})
# Output:
# <?xml version="1.0"?>
# <album>
#   <id>1</id>
#   <name>RF</name>
#   <artist_id>2</artist_id>
#   <artist>
#     <name>YJM</name>
#   </artist>
# </album>

to_xml also exists as a class and dataset method, both of which return all objects in the dataset:

Album.to_xml
Album.filter(:artist_id=>1).to_xml(:include=>:tags)

If you have an existing array of model instances you want to convert to XML, you can call the class to_xml method with the :array option:

Album.to_xml(:array=>[Album[1], Album[2]])

In addition to creating XML, this plugin also enables Sequel::Model classes to create instances directly from XML using the from_xml class method:

xml = album.to_xml
album = Album.from_xml(xml)

The array_from_xml class method exists to parse arrays of model instances from xml:

xml = Album.filter(:artist_id=>1).to_xml
albums = Album.array_from_xml(xml)

These does not necessarily round trip, since doing so would let users create model objects with arbitrary values. By default, from_xml will call set using values from the tags in the xml. If you want to specify the allowed fields, you can use the :fields option, which will call set_fields with the given fields:

Album.from_xml(album.to_xml, :fields=>%w'id name')

If you want to update an existing instance, you can use the from_xml instance method:

album.from_xml(xml)

Both of these allow creation of cached associated objects, if you provide the :associations option:

album.from_xml(xml, :associations=>:artist)

You can even provide options when setting up the associated objects:

album.from_xml(xml, :associations=>{:artist=>{:fields=>%w'id name', :associations=>:tags}})

Usage:

# Add XML output capability to all model subclass instances (called before loading subclasses)
Sequel::Model.plugin :xml_serializer

# Add XML output capability to Album class instances
Album.plugin :xml_serializer

Defined Under Namespace

Modules: ClassMethods, DatasetMethods, InstanceMethods