Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/branches/1-2-stable/activesupport/lib/active_support/json.rb

Revision 5498, 1.4 kB (checked in by sam, 2 years ago)

Merge [5486] from trunk.

Line 
1 require 'active_support/json/encoders'
2
3 module ActiveSupport
4   module JSON #:nodoc:
5     class CircularReferenceError < StandardError #:nodoc:
6     end
7    
8     # A string that returns itself as as its JSON-encoded form.
9     class Variable < String #:nodoc:
10       def to_json
11         self
12       end
13     end
14    
15     # When +true+, Hash#to_json will omit quoting string or symbol keys
16     # if the keys are valid JavaScript identifiers.  Note that this is
17     # technically improper JSON (all object keys must be quoted), so if
18     # you need strict JSON compliance, set this option to +false+.
19     mattr_accessor :unquote_hash_key_identifiers
20     @@unquote_hash_key_identifiers = true
21
22     class << self
23       REFERENCE_STACK_VARIABLE = :json_reference_stack
24      
25       def encode(value)
26         raise_on_circular_reference(value) do
27           Encoders[value.class].call(value)
28         end
29       end
30      
31       def can_unquote_identifier?(key)
32         return false unless unquote_hash_key_identifiers
33         key.to_s =~ /^[[:alpha:]_$][[:alnum:]_$]*$/
34       end
35      
36       protected
37         def raise_on_circular_reference(value)
38           stack = Thread.current[REFERENCE_STACK_VARIABLE] ||= []
39           raise CircularReferenceError, 'object references itself' if
40             stack.include? value
41           stack << value
42           yield
43         ensure
44           stack.pop
45         end
46     end
47   end
48 end
Note: See TracBrowser for help on using the browser.