2007-03-18 03:05:58 -04:00
|
|
|
require 'active_support/json/variable'
|
2007-05-18 17:16:43 -04:00
|
|
|
require 'active_support/json/encoders/object' # Require explicitly for rdoc.
|
|
|
|
Dir["#{File.dirname(__FILE__)}/encoders/**/*.rb"].each do |file|
|
|
|
|
basename = File.basename(file, '.rb')
|
|
|
|
unless basename == 'object'
|
|
|
|
require "active_support/json/encoders/#{basename}"
|
|
|
|
end
|
|
|
|
end
|
2007-03-18 03:05:58 -04:00
|
|
|
|
|
|
|
module ActiveSupport
|
|
|
|
module JSON
|
|
|
|
class CircularReferenceError < StandardError
|
|
|
|
end
|
|
|
|
|
|
|
|
class << self
|
|
|
|
REFERENCE_STACK_VARIABLE = :json_reference_stack #:nodoc:
|
|
|
|
|
|
|
|
# Converts a Ruby object into a JSON string.
|
2007-10-03 23:28:42 -04:00
|
|
|
def encode(value, options = {})
|
2007-03-18 03:05:58 -04:00
|
|
|
raise_on_circular_reference(value) do
|
2007-10-03 23:28:42 -04:00
|
|
|
value.send(:to_json, options)
|
2007-03-18 03:05:58 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
def raise_on_circular_reference(value) #:nodoc:
|
|
|
|
stack = Thread.current[REFERENCE_STACK_VARIABLE] ||= []
|
|
|
|
raise CircularReferenceError, 'object references itself' if
|
|
|
|
stack.include? value
|
|
|
|
stack << value
|
|
|
|
yield
|
|
|
|
ensure
|
|
|
|
stack.pop
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|