Module: SpriteKit::Serializer
- Defined in:
- mygame/lib/sprite_kit/serializer.rb
Class Method Summary collapse
-
.to_json(object, spacer = " ", depth = 1) ⇒ Object
down and dirty to_json.
-
.to_json_value(value, spacer, depth) ⇒ Object
Primitive for turning a value into a JSON string.
Class Method Details
.to_json(object, spacer = " ", depth = 1) ⇒ Object
down and dirty to_json. Just hashes, numbers, symbols, strings, array, and nil.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'mygame/lib/sprite_kit/serializer.rb', line 35 def self.to_json(object, spacer = " ", depth = 1) strs = [] if object.is_a?(Array) object.each do |v| strs << to_json_value(v, spacer, depth) end elsif Object.is_a?(Hash) object.each do |k, v| strs << "#{spacer * depth}\"#{k}\": #{to_json_value(v, spacer, depth)}" end else raise "Only hashes and arrays are supported." end "{\n" + strs.join(",\n") + "\n}" end |
.to_json_value(value, spacer, depth) ⇒ Object
Primitive for turning a value into a JSON string. Right now it supports Hash, Numeric, String, Symbol, Array, and nil.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'mygame/lib/sprite_kit/serializer.rb', line 4 def self.to_json_value(value, spacer, depth) return "null" if value.nil? return value.to_s if value.is_a?(Numeric) return "\"#{value.to_s.gsub('"', "'\"'")}\"" if value.is_a?(String) || value.is_a?(Symbol) if value.is_a?(Hash) inner_depth = depth + 1 strings = value.map do |k, v| "#{spacer * inner_depth}" + to_json_value(k, spacer, inner_depth) + ": " + to_json_value(v, spacer, inner_depth) end.join(",\n") leading_space = "#{spacer * depth}" return "{\n" + strings + "\n#{leading_space}}" end if value.is_a?(Array) inner_depth = depth + 1 strings = value.map do |v| "#{spacer * inner_depth}" + to_json_value(v, spacer, inner_depth) end.join(",\n") leading_space = "#{spacer * depth}" return "[\n" + strings + "\n#{leading_space}]" end raise "Value is not of type String, Symbol, Hash, Numeric, Array, or nil" end |