Skip to content

Instantly share code, notes, and snippets.

@DBA
Created April 7, 2010 23:42
Show Gist options
  • Save DBA/359582 to your computer and use it in GitHub Desktop.
Save DBA/359582 to your computer and use it in GitHub Desktop.
require 'builder'
class LogEntry
include Mongoid::Document
include Mongoid::Timestamps
#TODO put the two methods at include Mongoid::Serializers::Xml (or something alike)
# Fields
field :app_key, :type => String
field :level, :type => String, :default => 'INFO'
field :event_id, :type => String, :default => nil
field :message, :type => String, :default => nil
field :data, :type => Hash, :default => {}
field :more_data, :type => Array, :default => []
# Validations
validates_presence_of [:app_key, :level]
# Indexes
index :app_key, :unique => false
index :level, :unique => false
index :data, :unique => false
def to_xml(options = {})
options[:indent] ||= 2
builder = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
builder.instruct! unless options[:skip_instruct]
builder.tag!(_type) do
unless options[:skip_internals]
builder.internal_mongo_document_id _id
builder.internal_mongo_document_type _type
end
fields.each_value do |field|
serialize_field(field.name, self.send(field.name), field.type, options) if field.accessible?
end
end
end
private
def serialize_field(name = nil, value = nil, type = nil, options = {})
return unless name
builder = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
case value
when ::Hash
value.to_xml(options.merge({ :root => name, :skip_instruct => true }))
when ::Array
builder.tag! name, :type => "Array" do
value.each { |v| serialize_field('value', v, nil, options) }
end
else
type ? builder.tag!(name, value, :type => type) : builder.tag!(name, value)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment