2009-06-05 21:25:07 -04:00
|
|
|
require 'active_support/core_ext/module/attribute_accessors'
|
2009-06-17 22:27:36 -04:00
|
|
|
require 'active_support/core_ext/module/delegation'
|
2011-04-18 15:39:15 -04:00
|
|
|
require 'multi_json'
|
2009-06-05 21:25:07 -04:00
|
|
|
|
|
|
|
module ActiveSupport
|
|
|
|
# Look for and parse json strings that look like ISO 8601 times.
|
|
|
|
mattr_accessor :parse_json_times
|
|
|
|
|
|
|
|
module JSON
|
|
|
|
class << self
|
2011-04-18 15:39:15 -04:00
|
|
|
def decode(json, options ={})
|
|
|
|
data = MultiJson.decode(json, options)
|
|
|
|
if ActiveSupport.parse_json_times
|
|
|
|
convert_dates_from(data)
|
|
|
|
else
|
|
|
|
data
|
|
|
|
end
|
|
|
|
end
|
2009-06-05 21:25:07 -04:00
|
|
|
|
2011-04-18 15:39:15 -04:00
|
|
|
def engine
|
|
|
|
MultiJson.engine
|
2009-06-05 21:25:07 -04:00
|
|
|
end
|
2011-04-18 15:39:15 -04:00
|
|
|
alias :backend :engine
|
2009-06-05 21:25:07 -04:00
|
|
|
|
2011-04-18 15:39:15 -04:00
|
|
|
def engine=(name)
|
|
|
|
MultiJson.engine = name
|
2009-06-05 21:25:07 -04:00
|
|
|
end
|
2011-04-18 15:39:15 -04:00
|
|
|
alias :backend= :engine=
|
2009-06-05 21:25:07 -04:00
|
|
|
|
|
|
|
def with_backend(name)
|
|
|
|
old_backend, self.backend = backend, name
|
|
|
|
yield
|
|
|
|
ensure
|
|
|
|
self.backend = old_backend
|
|
|
|
end
|
2010-02-05 13:16:30 -05:00
|
|
|
|
2011-04-18 15:39:15 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def convert_dates_from(data)
|
|
|
|
case data
|
|
|
|
when nil
|
|
|
|
nil
|
|
|
|
when DATE_REGEX
|
2010-02-05 13:16:30 -05:00
|
|
|
begin
|
2011-04-18 15:39:15 -04:00
|
|
|
DateTime.parse(data)
|
|
|
|
rescue ArgumentError
|
|
|
|
data
|
2010-02-05 13:16:30 -05:00
|
|
|
end
|
2011-04-18 15:39:15 -04:00
|
|
|
when Array
|
|
|
|
data.map! { |d| convert_dates_from(d) }
|
|
|
|
when Hash
|
|
|
|
data.each do |key, value|
|
|
|
|
data[key] = convert_dates_from(value)
|
|
|
|
end
|
|
|
|
else
|
|
|
|
data
|
2010-02-05 13:16:30 -05:00
|
|
|
end
|
|
|
|
end
|
2009-06-05 21:25:07 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|