Skip to content

Instantly share code, notes, and snippets.

@mauricio
Created April 9, 2013 18:09
Show Gist options
  • Select an option

  • Save mauricio/5347965 to your computer and use it in GitHub Desktop.

Select an option

Save mauricio/5347965 to your computer and use it in GitHub Desktop.
gem 'activemodel'
require 'active_model'
module Serializable
include ActiveModel::Serializers::Xml
def self.included(base)
base.extend ClassMethods
base.extend ActiveModel::Naming
end
def initialize( attrs = {} )
attrs.each do |key,value|
send("#{key}=", value)
end
end
module ClassMethods
def define_attributes( *keys )
attr_accessor *keys
define_method("attributes") do
values = {}
keys.each do |key|
values[key] = send(key)
end
values
end
end
end
end
class User
include Serializable
define_attributes :name, :products, :company
end
class Product
include Serializable
define_attributes :name, :price
end
class Company
include Serializable
define_attributes :name
end
company = Company.new( :name => 'Some Company' )
products = [
Product.new(:name => 'First one', :price => 30),
Product.new(:name => 'Second one', :price => 20)
]
user = User.new( :products => products, :company => company, :name => 'Some User' )
puts user.to_xml( :methods => [ :products, :company, :name ] )
<?xml version="1.0" encoding="UTF-8"?>
<user>
<company>
<name>Some Company</name>
</company>
<name>Some User</name>
<products type="array">
<product>
<name>First one</name>
<price type="integer">30</price>
</product>
<product>
<name>Second one</name>
<price type="integer">20</price>
</product>
</products>
</user>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment