Class: Psych::Visitors::YAMLTree

Inherits:
Visitor show all
Defined in:
lib/psych/visitors/yaml_tree.rb,
ext/psych/psych_yaml_tree.c

Overview

YAMLTree builds a YAML ast given a Ruby object. For example:

builder = Psych::Visitors::YAMLTree.new
builder << { :foo => 'bar' }
builder.tree # => #<Psych::Nodes::Stream .. }

Direct Known Subclasses

Stream, JSONTree, RestrictedYAMLTree

Defined Under Namespace

Classes: Registrar

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(emitter, ss, options) ⇒ YAMLTree

Returns a new instance of YAMLTree.



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
# File 'lib/psych/visitors/yaml_tree.rb', line 51

def initialize emitter, ss, options
  super()
  @started    = false
  @finished   = false
  @emitter    = emitter
  @st         = Registrar.new
  @ss         = ss
  @options    = options
  @line_width = options[:line_width]
  if @line_width && @line_width < 0
    if @line_width == -1
      # Treat -1 as unlimited line-width, same as libyaml does.
      @line_width = nil
    else
      fail(ArgumentError, "Invalid line_width #{@line_width}, must be non-negative or -1 for unlimited.")
    end
  end
  @stringify_names = options[:stringify_names]
  @coders     = []

  @dispatch_cache = Hash.new do |h,klass|
    method = "visit_#{(klass.name || '').split('::').join('_')}"

    method = respond_to?(method) ? method : h[klass.superclass]

    raise(TypeError, "can't dump #{klass.name}") unless method

    h[klass] = method
  end.compare_by_identity
end

Instance Attribute Details

#finishedObject (readonly) Also known as: finished?

Returns the value of attribute finished.



40
41
42
# File 'lib/psych/visitors/yaml_tree.rb', line 40

def finished
  @finished
end

#startedObject (readonly) Also known as: started?

Returns the value of attribute started.



40
41
42
# File 'lib/psych/visitors/yaml_tree.rb', line 40

def started
  @started
end

Class Method Details

.create(options = {}, emitter = nil) ⇒ Object



44
45
46
47
48
49
# File 'lib/psych/visitors/yaml_tree.rb', line 44

def self.create options = {}, emitter = nil
  emitter      ||= TreeBuilder.new
  class_loader = ClassLoader.new
  ss           = ScalarScanner.new class_loader
  new(emitter, ss, options)
end

Instance Method Details

#accept(target) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/psych/visitors/yaml_tree.rb', line 119

def accept target
  # return any aliases we find
  if @st.key? target
    oid         = @st.id_for target
    node        = @st.node_for target
    anchor      = oid.to_s
    node.anchor = anchor
    return @emitter.alias anchor
  end

  if target.respond_to?(:encode_with)
    dump_coder target
  else
    send(@dispatch_cache[target.class], target)
  end
end

#finishObject



88
89
90
91
92
# File 'lib/psych/visitors/yaml_tree.rb', line 88

def finish
  @emitter.end_stream.tap do
    @finished = true
  end
end

#push(object) ⇒ Object Also known as: <<



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/psych/visitors/yaml_tree.rb', line 99

def push object
  start unless started?
  version = []
  version = [1,1] if @options[:header]

  case @options[:version]
  when Array
    version = @options[:version]
  when String
    version = @options[:version].split('.').map { |x| x.to_i }
  else
    version = [1,1]
  end if @options.key? :version

  @emitter.start_document version, [], false
  accept object
  @emitter.end_document !@emitter.streaming?
end

#start(encoding = Nodes::Stream::UTF8) ⇒ Object



82
83
84
85
86
# File 'lib/psych/visitors/yaml_tree.rb', line 82

def start encoding = Nodes::Stream::UTF8
  @emitter.start_stream(encoding).tap do
    @started = true
  end
end

#treeObject



94
95
96
97
# File 'lib/psych/visitors/yaml_tree.rb', line 94

def tree
  finish unless finished?
  @emitter.root
end

#visit_Array(o) ⇒ Object



386
387
388
389
390
391
392
# File 'lib/psych/visitors/yaml_tree.rb', line 386

def visit_Array o
  if o.class == ::Array
    visit_Enumerator o
  else
    visit_array_subclass o
  end
end

#visit_BasicObject(o) ⇒ Object



412
413
414
415
416
417
418
419
420
421
422
# File 'lib/psych/visitors/yaml_tree.rb', line 412

def visit_BasicObject o
  tag = Psych.dump_tags[o.class]
  tag ||= "!ruby/marshalable:#{o.class.name}"

  map = @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK)
  register(o, map)

  o.marshal_dump.each(&method(:accept))

  @emitter.end_mapping
end

#visit_BigDecimal(o) ⇒ Object



286
287
288
# File 'lib/psych/visitors/yaml_tree.rb', line 286

def visit_BigDecimal o
  @emitter.scalar o._dump, nil, '!ruby/object:BigDecimal', false, false, Nodes::Scalar::ANY
end

#visit_Class(o) ⇒ Object

Raises:

  • (TypeError)


349
350
351
352
# File 'lib/psych/visitors/yaml_tree.rb', line 349

def visit_Class o
  raise TypeError, "can't dump anonymous class: #{o}" unless o.name
  register o, @emitter.scalar(o.name, nil, '!ruby/class', false, false, Nodes::Scalar::SINGLE_QUOTED)
end

#visit_Complex(o) ⇒ Object



259
260
261
262
263
264
265
266
267
# File 'lib/psych/visitors/yaml_tree.rb', line 259

def visit_Complex o
  register o, @emitter.start_mapping(nil, '!ruby/object:Complex', false, Nodes::Mapping::BLOCK)

  ['real', o.real.to_s, 'image', o.imag.to_s].each do |m|
    @emitter.scalar m, nil, nil, true, false, Nodes::Scalar::ANY
  end

  @emitter.end_mapping
end

#visit_Data(o) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/psych/visitors/yaml_tree.rb', line 165

def visit_Data o
  ivars = o.instance_variables
  if ivars.empty?
    tag = ['!ruby/data', o.class.name].compact.join(':')
    register o, @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK)
    o.members.each do |member|
      @emitter.scalar member.to_s, nil, nil, true, false, Nodes::Scalar::ANY
      accept o.send member
    end
    @emitter.end_mapping

  else
    tag = ['!ruby/data-with-ivars', o.class.name].compact.join(':')
    node = @emitter.start_mapping(nil, tag, false, Psych::Nodes::Mapping::BLOCK)
    register(o, node)

    # Dump the members
    accept 'members'
    @emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK
    o.members.each do |member|
      @emitter.scalar member.to_s, nil, nil, true, false, Nodes::Scalar::ANY
      accept o.send member
    end
    @emitter.end_mapping

    # Dump the ivars
    accept 'ivars'
    @emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK
    ivars.each do |ivar|
      accept ivar.to_s
      accept o.instance_variable_get ivar
    end
    @emitter.end_mapping

    @emitter.end_mapping
  end
end

#visit_Date(o) ⇒ Object



229
230
231
232
# File 'lib/psych/visitors/yaml_tree.rb', line 229

def visit_Date o
  formatted = format_date o
  register o, @emitter.scalar(formatted, nil, nil, true, false, Nodes::Scalar::ANY)
end

#visit_DateTime(o) ⇒ Object



234
235
236
237
238
239
# File 'lib/psych/visitors/yaml_tree.rb', line 234

def visit_DateTime o
  t = o.italy
  formatted = format_time t, t.offset.zero?
  tag = '!ruby/object:DateTime'
  register o, @emitter.scalar(formatted, nil, tag, false, false, Nodes::Scalar::ANY)
end

#visit_Encoding(o) ⇒ Object



144
145
146
147
# File 'lib/psych/visitors/yaml_tree.rb', line 144

def visit_Encoding o
  tag = "!ruby/encoding"
  @emitter.scalar o.name, nil, tag, false, false, Nodes::Scalar::ANY
end

#visit_Enumerator(o) ⇒ Object



394
395
396
397
398
# File 'lib/psych/visitors/yaml_tree.rb', line 394

def visit_Enumerator o
  register o, @emitter.start_sequence(nil, nil, true, Nodes::Sequence::BLOCK)
  o.each { |c| accept c }
  @emitter.end_sequence
end

#visit_Exception(o) ⇒ Object



217
218
219
# File 'lib/psych/visitors/yaml_tree.rb', line 217

def visit_Exception o
  dump_exception o, o.message.to_s
end

#visit_Float(o) ⇒ Object



275
276
277
278
279
280
281
282
283
284
# File 'lib/psych/visitors/yaml_tree.rb', line 275

def visit_Float o
  if o.nan?
    @emitter.scalar '.nan', nil, nil, true, false, Nodes::Scalar::ANY
  elsif o.infinite?
    @emitter.scalar((o.infinite? > 0 ? '.inf' : '-.inf'),
      nil, nil, true, false, Nodes::Scalar::ANY)
  else
    @emitter.scalar o.to_s, nil, nil, true, false, Nodes::Scalar::ANY
  end
end

#visit_Hash(o) ⇒ Object



362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/psych/visitors/yaml_tree.rb', line 362

def visit_Hash o
  if o.class == ::Hash
    register(o, @emitter.start_mapping(nil, nil, true, Psych::Nodes::Mapping::BLOCK))
    o.each do |k,v|
      accept(@stringify_names && Symbol === k ? k.to_s : k)
      accept v
    end
    @emitter.end_mapping
  else
    visit_hash_subclass o
  end
end

#visit_Integer(o) ⇒ Object Also known as: visit_TrueClass, visit_FalseClass



269
270
271
# File 'lib/psych/visitors/yaml_tree.rb', line 269

def visit_Integer o
  @emitter.scalar o.to_s, nil, nil, true, false, Nodes::Scalar::ANY
end

#visit_Module(o) ⇒ Object

Raises:

  • (TypeError)


344
345
346
347
# File 'lib/psych/visitors/yaml_tree.rb', line 344

def visit_Module o
  raise TypeError, "can't dump anonymous module: #{o}" unless o.name
  register o, @emitter.scalar(o.name, nil, '!ruby/module', false, false, Nodes::Scalar::SINGLE_QUOTED)
end

#visit_NameError(o) ⇒ Object



221
222
223
# File 'lib/psych/visitors/yaml_tree.rb', line 221

def visit_NameError o
  dump_exception o, o.message.to_s
end

#visit_NilClass(o) ⇒ Object



400
401
402
# File 'lib/psych/visitors/yaml_tree.rb', line 400

def visit_NilClass o
  @emitter.scalar('', nil, 'tag:yaml.org,2002:null', true, false, Nodes::Scalar::ANY)
end

#visit_Object(o) ⇒ Object Also known as: visit_Delegator



149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/psych/visitors/yaml_tree.rb', line 149

def visit_Object o
  tag = Psych.dump_tags[o.class]
  unless tag
    klass = o.class == Object ? nil : o.class.name
    tag   = ['!ruby/object', klass].compact.join(':')
  end

  map = @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK)
  register(o, map)

  dump_ivars o
  @emitter.end_mapping
end

#visit_Psych_Omap(o) ⇒ Object



136
137
138
139
140
141
142
# File 'lib/psych/visitors/yaml_tree.rb', line 136

def visit_Psych_Omap o
  seq = @emitter.start_sequence(nil, 'tag:yaml.org,2002:omap', false, Nodes::Sequence::BLOCK)
  register(o, seq)

  o.each { |k,v| visit_Hash k => v }
  @emitter.end_sequence
end

#visit_Psych_Set(o) ⇒ Object



375
376
377
378
379
380
381
382
383
384
# File 'lib/psych/visitors/yaml_tree.rb', line 375

def visit_Psych_Set o
  register(o, @emitter.start_mapping(nil, '!set', false, Psych::Nodes::Mapping::BLOCK))

  o.each do |k,v|
    accept(@stringify_names && Symbol === k ? k.to_s : k)
    accept v
  end

  @emitter.end_mapping
end

#visit_Range(o) ⇒ Object



354
355
356
357
358
359
360
# File 'lib/psych/visitors/yaml_tree.rb', line 354

def visit_Range o
  register o, @emitter.start_mapping(nil, '!ruby/range', false, Nodes::Mapping::BLOCK)
  ['begin', o.begin, 'end', o.end, 'excl', o.exclude_end?].each do |m|
    accept m
  end
  @emitter.end_mapping
end

#visit_Rational(o) ⇒ Object



246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/psych/visitors/yaml_tree.rb', line 246

def visit_Rational o
  register o, @emitter.start_mapping(nil, '!ruby/object:Rational', false, Nodes::Mapping::BLOCK)

  [
    'denominator', o.denominator.to_s,
    'numerator', o.numerator.to_s
  ].each do |m|
    @emitter.scalar m, nil, nil, true, false, Nodes::Scalar::ANY
  end

  @emitter.end_mapping
end

#visit_Regexp(o) ⇒ Object



225
226
227
# File 'lib/psych/visitors/yaml_tree.rb', line 225

def visit_Regexp o
  register o, @emitter.scalar(o.inspect, nil, '!ruby/regexp', false, false, Nodes::Scalar::ANY)
end

#visit_String(o) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/psych/visitors/yaml_tree.rb', line 290

def visit_String o
  plain = true
  quote = true
  style = Nodes::Scalar::PLAIN
  tag   = nil

  if binary?(o)
    o     = [o].pack('m0')
    tag   = '!binary' # FIXME: change to below when syck is removed
    #tag   = 'tag:yaml.org,2002:binary'
    style = Nodes::Scalar::LITERAL
    plain = false
    quote = false
  elsif o.match?(/\n(?!\Z)/)  # match \n except blank line at the end of string
    style = Nodes::Scalar::LITERAL
  elsif o == '<<'
    style = Nodes::Scalar::SINGLE_QUOTED
    tag   = 'tag:yaml.org,2002:str'
    plain = false
    quote = false
  elsif o == 'y' || o == 'Y' || o == 'n' || o == 'N'
    style = Nodes::Scalar::DOUBLE_QUOTED
  elsif @line_width && o.length > @line_width
    style = Nodes::Scalar::FOLDED
  elsif o.match?(/^[^[:word:]][^"]*$/)
    style = Nodes::Scalar::DOUBLE_QUOTED
  elsif not String === @ss.tokenize(o) or /\A0[0-7]*[89]/.match?(o)
    style = Nodes::Scalar::SINGLE_QUOTED
  end

  is_primitive = o.class == ::String
  ivars = is_primitive ? [] : o.instance_variables

  if ivars.empty?
    unless is_primitive
      tag = "!ruby/string:#{o.class}"
      plain = false
      quote = false
    end
    @emitter.scalar o, nil, tag, plain, quote, style
  else
    maptag = '!ruby/string'.dup
    maptag << ":#{o.class}" unless o.class == ::String

    register o, @emitter.start_mapping(nil, maptag, false, Nodes::Mapping::BLOCK)
    @emitter.scalar 'str', nil, nil, true, false, Nodes::Scalar::ANY
    @emitter.scalar o, nil, tag, plain, quote, style

    dump_ivars o

    @emitter.end_mapping
  end
end

#visit_Struct(o) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/psych/visitors/yaml_tree.rb', line 203

def visit_Struct o
  tag = ['!ruby/struct', o.class.name].compact.join(':')

  register o, @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK)
  o.members.each do |member|
    @emitter.scalar member.to_s, nil, nil, true, false, Nodes::Scalar::ANY
    accept o[member]
  end

  dump_ivars o

  @emitter.end_mapping
end

#visit_Symbol(o) ⇒ Object



404
405
406
407
408
409
410
# File 'lib/psych/visitors/yaml_tree.rb', line 404

def visit_Symbol o
  if o.empty?
    @emitter.scalar "", nil, '!ruby/symbol', false, false, Nodes::Scalar::ANY
  else
    @emitter.scalar ":#{o}", nil, nil, true, false, Nodes::Scalar::ANY
  end
end

#visit_Time(o) ⇒ Object



241
242
243
244
# File 'lib/psych/visitors/yaml_tree.rb', line 241

def visit_Time o
  formatted = format_time o
  register o, @emitter.scalar(formatted, nil, nil, true, false, Nodes::Scalar::ANY)
end