Class: Psych::Visitors::ToRuby

Inherits:
Object
  • Object
show all
Defined in:
lib/psych/exts.rb

Overview

The next step is to convert the AST to a Ruby object. Psych does this using the visitor pattern with the ToRuby visitor. Here we patch ToRuby rather than inherit from it as it makes the last step a little easier.

Instance Method Summary collapse

Instance Method Details

#revive_hash(hash, o) ⇒ Object

This is the method for creating hashes. There may be problems with Yaml mappings that have tags.



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
# File 'lib/psych/exts.rb', line 38

def revive_hash(hash, o)
  o.children.each_slice(2) do |k, v|
    key = accept(k)
    val = accept(v)

    # This is the important bit. If the value is a scalar,
    # we replace it with the desired hash.
    if v.is_a? ::Psych::Nodes::Scalar
      val = Graml::Data.new(value: val, line: v.line) # line is 0 based, so + 1
    end

    # Code dealing with << (for merging hashes) omitted.
    # If you need this you will probably need to copy it
    # in here. See the method:
    # https://github.com/tenderlove/psych/blob/v2.0.13/lib/psych/visitors/to_ruby.rb#L333-L365
    if key == "<<" && k.tag != "tag:yaml.org,2002:str"
      case v
      when Psych::Nodes::Alias, Psych::Nodes::Mapping
        begin
          hash.merge! val
        rescue TypeError
          hash[key] = val
        end
      when Psych::Nodes::Sequence
        begin
          h = {}
          val.reverse_each do |value|
            h.merge! value
          end
          hash.merge! h
        rescue TypeError
          hash[key] = val
        end
      else
        hash[key] = val
      end
    else
      hash[key] = val
    end
  end
  hash
end