123456789_123456789_123456789_123456789_123456789_

Module: ActiveModel::Serializers::Xml

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Instance Chain:
Defined in: activemodel/lib/active_model/serializers/xml.rb

Overview

Active Model XML Serializer

Class Method Summary

Instance Method Summary

::ActiveModel::Serialization - Included

#serializable_hash

Returns a serialized hash of your object.

DSL Calls

included

[ GitHub ]


14
15
16
# File 'activemodel/lib/active_model/serializers/xml.rb', line 14

included do
  extend ActiveModel::Naming
end

Instance Method Details

#from_xml(xml)

Sets the model attributes from an XML string. Returns self.

class Person
  include ActiveModel::Serializers::Xml

  attr_accessor :name, :age, :awesome

  def attributes=(hash)
    hash.each do |key, value|
      instance_variable_set("@#{key}", value)
    end
  end

  def attributes
    instance_values
  end
end

xml = { name: 'bob', age: 22, awesome:true }.to_xml
person = Person.new
person.from_xml(xml) # => #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
person.name          # => "bob"
person.age           # => 22
person.awesome       # => true
[ GitHub ]

  
# File 'activemodel/lib/active_model/serializers/xml.rb', line 232

def from_xml(xml)
  self.attributes = Hash.from_xml(xml).values.first
  self
end

#to_xml(options = {}, &block)

Returns XML representing the model. Configuration can be passed through options.

Without any options, the returned XML string will include all the model's attributes.

user = User.find(1)
user.to_xml

<?xml version="1.0" encoding="UTF-8"?>
<user>
  <id type="integer">1</id>
  <name>David</name>
  <age type="integer">16</age>
  <created-at type="dateTime">2011-01-30T22:29:23Z</created-at>
</user>

The :only and :except options can be used to limit the attributes included, and work similar to the attributes method.

To include the result of some method calls on the model use :methods.

To include associations use :include.

For further documentation, see ActiveRecord::Serialization#to_xml

[ GitHub ]

  
# File 'activemodel/lib/active_model/serializers/xml.rb', line 204

def to_xml(options = {}, &block)
  Serializer.new(self, options).serialize(&block)
end