class VV::JSON

Public Class Methods

default_max() click to toggle source
# File lib/vv/serialization/json.rb, line 3
def self.default_max
  1.mebibyte
end
generate(object, maximum_bytes=nil, **kwargs) click to toggle source
# File lib/vv/serialization/json.rb, line 7
def self.generate object,
                  maximum_bytes=nil,
                  **kwargs

  max = maximum_bytes || self.default_max

  generator = self.new( max, **kwargs )
  generator.serialize object
end
new(maximum_bytes, float_kwargs: nil) click to toggle source
# File lib/vv/serialization/json.rb, line 17
def initialize maximum_bytes,
               float_kwargs: nil

  @max = maximum_bytes
  @response = ""
  @float_kwargs = float_kwargs || {}
end

Public Instance Methods

check_for_size_failure!() click to toggle source
# File lib/vv/serialization/json.rb, line 76
def check_for_size_failure!
  size_failure! if @response.size > @max
end
default_max() click to toggle source
# File lib/vv/serialization/json.rb, line 72
def default_max
  self.class.default_max
end
serialize(object) click to toggle source
# File lib/vv/serialization/json.rb, line 25
def serialize object

  self.check_for_size_failure!

  case object
  when Hash
    @response += "{"

    object.each do |key, value|
      self.serialize! key.to_s
      @response += ":"

      self.serialize! value
      @response += ","
    end

    @response.chomp! ","
    @response += "}"
  when Array
    @response += "["

    object.each do |value|
      self.serialize! value
      @response += ","
    end

    @response.chomp! ","
    @response += "]"
  when String
    self.size_failure! if ( object.size + 2 ) > @max
    @response += object.to_json
  when Float
    @response += object.vv_json( **@float_kwargs )
  else
    if object.respond_to? :vv_json
      @response += object.vv_json
    else
      fail "VV::JSON cannot generate JSON for `#{object.class}`."
    end
  end

  self.check_for_size_failure!

  @response
end
Also aliased as: serialize!
serialize!(object)
Alias for: serialize
size_failure!() click to toggle source
# File lib/vv/serialization/json.rb, line 80
def size_failure!
  if @max == self.default_max
    fail "VV::JSON generation size exceeds default max of 1 MiB"
  else
    fail "VV::JSON generation size exceeds max of `#{@max}` bytes"
  end
end