File: xml_serializer.rb

package info (click to toggle)
ruby-rgen 0.10.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,428 kB
  • sloc: ruby: 11,344; xml: 1,368; yacc: 72; makefile: 10
file content (98 lines) | stat: -rw-r--r-- 2,277 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
module RGen

module Serializer

class XMLSerializer

  INDENT_SPACE = 2
  
	def initialize(file)
    @indent = 0
    @lastStartTag = nil
    @textContent = false
    @file = file
	end
	
	def serialize(rootElement)
		raise "Abstract class, overwrite method in subclass!"
	end
  
  def startTag(tag, attributes={})
    @textContent = false
    handleLastStartTag(false, true)
    if attributes.is_a?(Hash)
      attrString = attributes.keys.collect{|k| "#{k}=\"#{attributes[k]}\""}.join(" ")
    else
      attrString = attributes.collect{|pair| "#{pair[0]}=\"#{pair[1]}\""}.join(" ")
    end
    @lastStartTag = " "*@indent*INDENT_SPACE + "<#{tag} "+attrString
    @indent += 1
  end
  
  def endTag(tag)
    @indent -= 1
    unless handleLastStartTag(true, true)
      output " "*@indent*INDENT_SPACE unless @textContent
      output "</#{tag}>\n"
    end
    @textContent = false
  end

  def writeText(text)
    handleLastStartTag(false, false)
    output "#{text}"
    @textContent = true
  end  
	
	protected

  def eAllReferences(element)
    @eAllReferences ||= {}
    @eAllReferences[element.class] ||= element.class.ecore.eAllReferences
  end

  def eAllAttributes(element)
    @eAllAttributes ||= {}
    @eAllAttributes[element.class] ||= element.class.ecore.eAllAttributes
  end
    
  def eAllStructuralFeatures(element)
    @eAllStructuralFeatures ||= {}
    @eAllStructuralFeatures[element.class] ||= element.class.ecore.eAllStructuralFeatures
  end

	def eachReferencedElement(element, refs, &block)
		refs.each do |r|
			targetElements = element.getGeneric(r.name)
			targetElements = [targetElements] unless targetElements.is_a?(Array)
			targetElements.each do |te|
				yield(r,te)
			end
		end			
	end  

  def containmentReferences(element)
    @containmentReferences ||= {}
    @containmentReferences[element.class] ||= eAllReferences(element).select{|r| r.containment}
  end
  
  private
  
  def handleLastStartTag(close, newline)
    return false unless @lastStartTag
    output @lastStartTag
    output close ? "/>" : ">"
    output "\n" if newline
    @lastStartTag = nil
    true
  end
  
  def output(text)
    @file.write(text)
  end
  
end

end

end