class PoisePython::Utils::PythonEncoder
Convert Ruby data structures to a Python literal. Overall similar to JSON but just different enough that I need to write this. Thanks Obama.
@since 1.0.0 @api private
Public Class Methods
new(root, depth_limit: 100)
click to toggle source
# File lib/poise_python/utils/python_encoder.rb, line 28 def initialize(root, depth_limit: 100) @root = root @depth_limit = depth_limit end
Public Instance Methods
encode()
click to toggle source
# File lib/poise_python/utils/python_encoder.rb, line 33 def encode encode_obj(@root, 0) end
Private Instance Methods
encode_array(obj, depth)
click to toggle source
# File lib/poise_python/utils/python_encoder.rb, line 64 def encode_array(obj, depth) middle = obj.map do |value| encode_obj(value, depth+1) end "[#{middle.join(',')}]" end
encode_hash(obj, depth)
click to toggle source
# File lib/poise_python/utils/python_encoder.rb, line 57 def encode_hash(obj, depth) middle = obj.map do |key, value| "#{encode_obj(key, depth+1)}:#{encode_obj(value, depth+1)}" end "{#{middle.join(',')}}" end
encode_obj(obj, depth)
click to toggle source
# File lib/poise_python/utils/python_encoder.rb, line 39 def encode_obj(obj, depth) raise ArgumentError.new("Depth limit exceeded") if depth > @depth_limit case obj when Hash encode_hash(obj, depth) when Array encode_array(obj, depth) when true 'True' when false 'False' when nil 'None' else obj.to_json end end