2013-04-03 09:42:45 -04:00
require 'singleton'
require 'fog/core/logger'
2012-04-25 10:31:28 -04:00
2011-08-09 14:39:43 -04:00
module Fog
2013-04-03 09:42:45 -04:00
class JSON
include Singleton
2013-04-03 11:37:03 -04:00
class LoadError < StandardError
attr_reader :data
def initialize ( message = '' , backtrace = [ ] , data = '' )
super ( message )
self . set_backtrace ( backtrace )
@data = data
end
end
2013-04-03 09:42:45 -04:00
module LegacyJSON
def encode ( obj )
:: JSON . generate ( obj )
end
def decode ( obj )
:: JSON . parse ( obj )
2013-04-03 11:37:03 -04:00
rescue :: JSON :: ParserError = > e
raise LoadError . new ( e . message , e . backtrace , obj )
2013-04-03 09:42:45 -04:00
end
end
module NewJSON
def encode ( obj )
2013-04-03 11:37:03 -04:00
:: MultiJson . encode ( obj )
2013-04-03 09:42:45 -04:00
end
def decode ( obj )
2013-04-03 11:37:03 -04:00
:: MultiJson . decode ( obj )
rescue MultiJson :: LoadError = > e
raise LoadError . new ( e . message , e . backtrace , obj )
2013-04-03 09:42:45 -04:00
end
end
begin
require 'multi_json'
include NewJSON
2013-04-03 11:37:03 -04:00
rescue Exception = > e
2013-04-03 09:42:45 -04:00
Fog :: Logger . deprecation " Defaulting to json library for json parsing. Please consider using multi_json library for the greatest performance/flexibility. "
require 'json'
include LegacyJSON
end
2011-08-09 14:39:43 -04:00
def self . sanitize ( data )
case data
when Array
data . map { | datum | sanitize ( datum ) }
when Hash
for key , value in data
data [ key ] = sanitize ( value )
end
when :: Time
data . strftime ( " %Y-%m-%dT%H:%M:%SZ " )
else
data
end
end
2012-04-25 10:31:28 -04:00
# Do the MultiJson introspection at this level so we can define our encode/decode methods and perform
# the introspection only once rather than once per call.
2012-12-14 13:41:39 -05:00
def self . encode ( obj )
2013-04-03 09:42:45 -04:00
Fog :: JSON . instance . encode ( obj )
2012-04-25 10:31:28 -04:00
end
2012-12-14 13:41:39 -05:00
def self . decode ( obj )
2013-04-03 09:42:45 -04:00
Fog :: JSON . instance . decode ( obj )
2012-04-25 10:31:28 -04:00
end
2011-08-09 14:39:43 -04:00
end
2012-04-25 12:42:42 -04:00
end