Sha256: 38d4319555bc103aac6248c9e9b5f2fe62ee631f80d24a39f40764bb3507c4ff

Contents?: true

Size: 1.09 KB

Versions: 4

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

class Panko::ObjectWriter
  def initialize
    @values = []
    @keys = []

    @next_key = nil
    @output = nil
  end

  def push_object(key = nil)
    @values << {}
    @keys << key
  end

  def push_array(key = nil)
    @values << []
    @keys << key
  end

  def push_key(key)
    @next_key = key
  end

  def push_value(value, key = nil)
    unless @next_key.nil?
      raise "push_value is called with key after push_key is called" unless key.nil?
      key = @next_key
      @next_key = nil
    end

    @values.last[key] = value.as_json
  end

  def push_json(value, key = nil)
    if value.is_a?(String)
      value = begin
        Oj.load(value)
      rescue
        nil
      end
    end

    push_value(value, key)
  end

  def pop
    result = @values.pop

    if @values.empty?
      @output = result
      return
    end

    scope_key = @keys.pop
    if scope_key.nil?
      @values.last << result
    else
      @values.last[scope_key] = result
    end
  end

  def output
    raise "Output is called before poping all" unless @values.empty?
    @output
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
panko_serializer-0.8.2 lib/panko/object_writer.rb
panko_serializer-0.8.1 lib/panko/object_writer.rb
panko_serializer-0.8.0 lib/panko/object_writer.rb
panko_serializer-0.7.9 lib/panko/object_writer.rb