Sha256: b525a578ba865a4abf09af46ed39e80b1163b76b05726ad1e531f3069665e1b2

Contents?: true

Size: 1.78 KB

Versions: 3

Compression:

Stored size: 1.78 KB

Contents

require "psych"

module SafeYAML
  class PsychHandler < Psych::Handler
    def initialize
      @anchors = {}
      @stack = []
      @current_key = nil
      @result = nil
    end

    def result
      @result
    end

    def add_to_current_structure(value, anchor=nil, quoted=nil)
      value = Transform.to_proper_type(value, quoted)

      @anchors[anchor] = value if anchor

      if @result.nil?
        @result = value
        @current_structure = @result
        return
      end

      case @current_structure
      when Array
        @current_structure.push(value)

      when Hash
        if @current_key.nil?
          @current_key = value

        else
          if @current_key == "<<"
            @current_structure.merge!(value)
          else
            @current_structure[@current_key] = value
          end

          @current_key = nil
        end

      else
        raise "Don't know how to add to a #{@current_structure.class}!"
      end
    end

    def end_current_structure
      @stack.pop
      @current_structure = @stack.last
    end

    def streaming?
      false
    end

    # event handlers
    def alias(anchor)
      add_to_current_structure(@anchors[anchor])
    end

    def scalar(value, anchor, tag, plain, quoted, style)
      add_to_current_structure(value, anchor, quoted)
    end

    def start_mapping(anchor, tag, implicit, style)
      map = {}
      self.add_to_current_structure(map, anchor)
      @current_structure = map
      @stack.push(map)
    end

    def end_mapping
      self.end_current_structure()
    end

    def start_sequence(anchor, tag, implicit, style)
      seq = []
      self.add_to_current_structure(seq, anchor)
      @current_structure = seq
      @stack.push(seq)
    end

    def end_sequence
      self.end_current_structure()
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
safe_yaml-0.6.3 lib/safe_yaml/psych_handler.rb
safe_yaml-0.6.2 lib/safe_yaml/psych_handler.rb
safe_yaml-0.6.1 lib/safe_yaml/psych_handler.rb