Class: Treat::Workers::Formatters::Serializers::XML
- Inherits:
-
Object
- Object
- Treat::Workers::Formatters::Serializers::XML
- Defined in:
- lib/treat/workers/formatters/serializers/xml.rb
Overview
Serialization of entities to XML format.
Class Method Summary collapse
- .escape(input) ⇒ Object
- .recurse(entity, options) ⇒ Object
-
.serialize(entity, options = {}) ⇒ Object
Serialize an entity tree in XML format.
Class Method Details
.escape(input) ⇒ Object
72 73 74 75 76 77 78 79 80 |
# File 'lib/treat/workers/formatters/serializers/xml.rb', line 72 def self.escape(input) result = input.to_s.dup result.gsub!("&", "&") result.gsub!("<", "<") result.gsub!(">", ">") result.gsub!("'", "'") result.gsub!("\"", """) result end |
.recurse(entity, options) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/treat/workers/formatters/serializers/xml.rb', line 23 def self.recurse(entity, ) spaces, string = '', '' [:indent].times { spaces << ' ' } attributes = " id='#{entity.id}'" if !entity.features.nil? && entity.features.size != 0 attributes << ' ' entity.features.each_pair do |feature, value| if value.is_a? Treat::Entities::Entity attributes << "#{feature}='#{value.id}' " else value = value.inspect if value.is_a?(Symbol) attributes << "#{feature}='#{escape(value)}' " end end ############ To be refactored unless entity.edges.empty? attributes << "edges='" a = [] entity.edges.each do |edge| a << ("{target: #{edge.target}, "+ "type: #{edge.type}, " + "directed: #{edge.directed}, " + "direction: #{edge.direction}}" ) end # Structs. attributes << a.join(',') + "'" end ############ End of ugly code end tag = entity.class.to_s.split('::')[-1].downcase string += "#{spaces}<#{tag}#{attributes}>" unless entity.is_a?(Treat::Entities::Token) string += "\n" end if entity.has_children? [:indent] += 1 entity.children.each do |child| string += self.recurse(child, ) end [:indent] -= 1 else string += "#{escape(entity.value)}" end unless entity.is_a?(Treat::Entities::Token) string += "#{spaces}" end string += "</#{tag}>\n" end |
.serialize(entity, options = {}) ⇒ Object
Serialize an entity tree in XML format.
Options:
-
(String) :file => a file to write to.
10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/treat/workers/formatters/serializers/xml.rb', line 10 def self.serialize(entity, = {}) [:file] ||= (entity.id.to_s + '.xml') [:indent] = 0 enc = entity.to_s.encoding.to_s.downcase string = "<?xml version=\"1.0\" " + "encoding=\"#{enc}\" ?>\n<treat>\n" val = self.recurse(entity, ) string += "#{val}\n</treat>" File.open([:file], 'w') do |f| f.write(string) end; return [:file] end |