Class: VV::JSON
Class Method Summary collapse
Instance Method Summary collapse
- #check_for_size_failure! ⇒ Object
- #default_max ⇒ Object
-
#initialize(maximum_bytes, float_kwargs: nil) ⇒ JSON
constructor
A new instance of JSON.
- #serialize(object) ⇒ Object (also: #serialize!)
- #size_failure! ⇒ Object
Constructor Details
#initialize(maximum_bytes, float_kwargs: nil) ⇒ JSON
Returns a new instance of JSON.
17 18 19 20 21 22 23 |
# File 'lib/vv/serialization/json.rb', line 17 def initialize maximum_bytes, float_kwargs: nil @max = maximum_bytes @response = "" @float_kwargs = float_kwargs || {} end |
Class Method Details
.default_max ⇒ Object
3 4 5 |
# File 'lib/vv/serialization/json.rb', line 3 def self.default_max 1.mebibyte end |
.generate(object, maximum_bytes = nil, **kwargs) ⇒ Object
7 8 9 10 11 12 13 14 15 |
# 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 |
Instance Method Details
#check_for_size_failure! ⇒ Object
76 77 78 |
# File 'lib/vv/serialization/json.rb', line 76 def check_for_size_failure! size_failure! if @response.size > @max end |
#default_max ⇒ Object
72 73 74 |
# File 'lib/vv/serialization/json.rb', line 72 def default_max self.class.default_max end |
#serialize(object) ⇒ Object Also known as: serialize!
25 26 27 28 29 30 31 32 33 34 35 36 37 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 |
# 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 |
#size_failure! ⇒ Object
80 81 82 83 84 85 86 |
# 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 |