Sha256: 88d380d87dd8b40073a0dba43166f5d35116721a27bb51b2df59cea8b2002e9e

Contents?: true

Size: 1.17 KB

Versions: 16

Compression:

Stored size: 1.17 KB

Contents

require 'json'

module Volt
  class EJSON
    def self.stringify(obj)
      encode(obj).to_json
    end

    def self.parse(str)
      decode(JSON.parse(str))
    end

    private

    def self.decode(obj)
      if Array === obj
        obj.map {|v| decode(v) }
      elsif Hash === obj
        if obj.size == 1 && (escape = obj['$escape'])
          return escape.map do |key, value|
            [key, decode(value)]
          end.to_h
        elsif obj.size == 1 && (time = obj['$date'])
          if time.is_a?(Fixnum)
            return Time.at(time / 1000.0)
          end
        end

        obj.map do |key, value|
          [key, decode(value)]
        end.to_h
      else
        obj
      end
    end

    def self.encode(obj)
      if Array === obj
        obj.map {|v| encode(v) }
      elsif Hash === obj
        obj.map do |key, value|
          if key == '$date'
            key = '$escape'
            value = {'$date' => encode(value)}
          else
            value = encode(value)
          end

          [key, value]
        end.to_h
      else
        if obj.is_a?(Time)
          {'$date' => obj.to_i * 1_000}
        else
          obj
        end
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
volt-0.9.5.pre9 lib/volt/utils/ejson.rb
volt-0.9.5.pre8 lib/volt/utils/ejson.rb
volt-0.9.5.pre7 lib/volt/utils/ejson.rb
volt-0.9.5.pre6 lib/volt/utils/ejson.rb
volt-0.9.5.pre5 lib/volt/utils/ejson.rb
volt-0.9.5.pre4 lib/volt/utils/ejson.rb
volt-0.9.5.pre3 lib/volt/utils/ejson.rb
volt-0.9.5.pre2 lib/volt/utils/ejson.rb
volt-0.9.5.pre1 lib/volt/utils/ejson.rb
volt-0.9.4 lib/volt/utils/ejson.rb
volt-0.9.4.pre5 lib/volt/utils/ejson.rb
volt-0.9.4.pre3 lib/volt/utils/ejson.rb
volt-0.9.4.pre2 lib/volt/utils/ejson.rb
volt-0.9.4.pre1 lib/volt/utils/ejson.rb
volt-0.9.3 lib/volt/utils/ejson.rb
volt-0.9.3.pre6 lib/volt/utils/ejson.rb