Class: DiffableYAML::DiffableYAMLTree

Inherits:
Psych::Visitors::YAMLTree
  • Object
show all
Defined in:
lib/diffable_yaml.rb

Overview

this dumps YAML with hashes / dicts in a consistent order so that text diffs make more sense

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

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



9
10
11
12
13
14
# File 'lib/diffable_yaml.rb', line 9

def self.create options = {}, emitter = nil
  preorder = options.delete(:preorder) || []
  instance = Psych::Visitors::YAMLTree.create options, emitter
  instance.instance_variable_set '@preorder', preorder
  instance
end

Instance Method Details

#visit_Hash(o) ⇒ Object



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
# File 'lib/diffable_yaml.rb', line 16

def visit_Hash o
  tag      = o.class == ::Hash ? nil : "!ruby/hash:#{o.class}"
  implicit = !tag

  register(o, @emitter.start_mapping( nil, 
                                      tag, 
                                      implicit, 
                                      Psych::Nodes::Mapping::BLOCK))

  @preorder.each do |key|
    if o.key? key
      accept key
      accept o[key]
    end
  end
  o.keys.map {|k|
    [k, k.to_s]
  }.sort {|(k_a, s_a), (k_b, s_b)|
    s_a <=> s_b
  }.each do |k, s|
    unless @preorder.include? k
      accept k
      accept o[k]
    end
  end

  @emitter.end_mapping
end

#visit_String(o) ⇒ Object



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
# File 'lib/diffable_yaml.rb', line 45

def visit_String o
  plain = false
  quote = false
  style = Psych::Nodes::Scalar::ANY

  if binary?(o)
    str   = [o].pack('m').chomp
    tag   = '!binary' # FIXME: change to below when syck is removed
    #tag   = 'tag:yaml.org,2002:binary'
    style = Psych::Nodes::Scalar::LITERAL
  else
    str   = o
    tag   = nil
    quote = !(String === @ss.tokenize(o))
    plain = !quote
    if str.index("\n")
      style = Psych::Nodes::Scalar::LITERAL
    end
  end

  ivars = find_ivars o

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

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

    dump_ivars o

    @emitter.end_mapping
  end
end