2 require 'rbyaml/events'
6 class SerializerError < YAMLError
10 def initialize(emitter, resolver, opts={})
14 @use_explicit_start = opts[:ExplicitStart]
15 @use_explicit_end = opts[:ExplicitEnd]
16 @use_version = opts[:UseVersion] && opts[:Version]
17 @use_tags = opts[:UseHeader]
18 @anchor_template = opts[:AnchorFormat] || "id%03d"
19 @serialized_nodes = {}
27 @emitter.emit(StreamStartEvent.new)
30 raise SerializerError.new("serializer is closed")
32 raise SerializerError.new("serializer is already opened")
38 raise SerializerError.new("serializer is not opened")
40 @emitter.emit(StreamEndEvent.new)
47 raise SerializerError.new("serializer is not opened")
49 raise SerializerError.new("serializer is closed")
51 @emitter.emit(DocumentStartEvent.new(@use_explicit_start,@use_version,@use_tags))
53 serialize_node(node,nil,nil)
54 @emitter.emit(DocumentEndEvent.new(@use_explicit_end))
55 @serialized_nodes = {}
61 if @anchors.include?(node)
62 @anchors[node] ||= generate_anchor(node)
65 if SequenceNode === node
66 for item in node.value
69 elsif MappingNode === node
70 for key,val in node.value
78 def generate_anchor(node)
80 @anchor_template % @last_anchor_id
83 def serialize_node(node,parent,index)
84 talias = @anchors[node]
85 if @serialized_nodes.include?(node)
86 @emitter.emit(AliasEvent.new(talias))
88 @serialized_nodes[node] = true
89 @resolver.descend_resolver(parent, index)
90 if ScalarNode === node
91 detected_tag = @resolver.resolve(ScalarNode, node.value, [true,false])
92 default_tag = @resolver.resolve(ScalarNode, node.value, [false,true])
93 implicit = (node.tag == detected_tag), (node.tag == default_tag)
94 @emitter.emit(ScalarEvent.new(talias, node.tag, implicit, node.value,node.style))
95 elsif SequenceNode === node
96 implicit = (node.tag == @resolver.resolve(SequenceNode, node.value, true))
97 @emitter.emit(SequenceStartEvent.new(talias, node.tag, implicit,node.flow_style))
99 for item in node.value
100 serialize_node(item,node,index)
103 @emitter.emit(SequenceEndEvent.new)
104 elsif MappingNode === node
105 implicit = (node.tag == @resolver.resolve(MappingNode, node.value, true))
106 @emitter.emit(MappingStartEvent.new(talias, node.tag, implicit,node.flow_style))
107 for key, value in node.value
108 serialize_node(key,node,nil)
109 serialize_node(value,node,key)
111 @emitter.emit(MappingEndEvent.new)