Halcyon
Halcyon

Reputation: 691

XML Serialization from class instance in Ruby with custom attributes

Let's say that I have the following classes in Ruby:

class Person
  attr_accessor :name, :car
end

class Car
  attr_accessor :maker
end

Is there a gem in ruby that would allow me to serialize an instance of Person to XML and allow me to add custom attributes to the XML tags as well? (preferably a declarative api, where I can either assign the attributes to a specific tag inside the declaration of the attr_accessor, or for all tags at once as a hash returned from a function).

For example, I want to achieve something like this:

<Person>
  <Name origin="American">
     Mark
  </Name>
  <Car from="My friend">
    <Maker>
      Honda
    </Maker>
  </Car>
</Person>

https://github.com/rails/activemodel-serializers-xml does not allow you to set custom attributes (the attributes function in the examples actually sets the tags, not the attributes). Overriding to_xml does not let me modify existing tags, and I'd rather not add new ones. Other gems such as Nokogiri seem to have a more hands on approach, where you manually build the xml instead of deriving it from the definition of a class. Thanks for the help.

Upvotes: 0

Views: 375

Answers (1)

Giuseppe Schembri
Giuseppe Schembri

Reputation: 857

You could include the module XML::Mapping you can see an example here.

You can call all node factory methods from the body of the mapping classes.

In order to set customs attributes in the XML document:

require 'xml/mapping'

class Person
  include XML::Mapping

  text_node :from, "@from" # ,:default_value=>"My friend" migth works as well

  def initialize
    # add this to the initialize method 
    # if :default_value=>"My friend" in text_node do not works
    @from = "My friend"
  end
end

Upvotes: 1

Related Questions