aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/json.rb
diff options
context:
space:
mode:
authorSam Stephenson <sam@37signals.com>2005-12-27 03:11:03 +0000
committerSam Stephenson <sam@37signals.com>2005-12-27 03:11:03 +0000
commite567a5eb1afe1ac38f1da37f1c1e3922bbf79d2a (patch)
tree47baca37670f0ad23d803c2f939199147efe4287 /activesupport/lib/active_support/json.rb
parent0b55ce7191b167d67ec7ccc7eb8db2e5fac4f2e1 (diff)
downloadrails-e567a5eb1afe1ac38f1da37f1c1e3922bbf79d2a.tar.gz
rails-e567a5eb1afe1ac38f1da37f1c1e3922bbf79d2a.tar.bz2
rails-e567a5eb1afe1ac38f1da37f1c1e3922bbf79d2a.zip
Add ActiveSupport::JSON and Object#to_json for converting Ruby objects to JSON strings
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@3356 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activesupport/lib/active_support/json.rb')
-rw-r--r--activesupport/lib/active_support/json.rb28
1 files changed, 28 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb
new file mode 100644
index 0000000000..77c7225c66
--- /dev/null
+++ b/activesupport/lib/active_support/json.rb
@@ -0,0 +1,28 @@
+require 'active_support/json/encoders'
+
+module ActiveSupport
+ module JSON #:nodoc:
+ class CircularReferenceError < StandardError; end
+
+ class << self
+ REFERENCE_STACK_VARIABLE = :json_reference_stack
+
+ def encode(value)
+ raise_on_circular_reference(value) do
+ Encoders[value.class].call(value)
+ end
+ end
+
+ protected
+ def raise_on_circular_reference(value)
+ 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