|
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 |
|---|
| 5 |
class CircularReferenceError < StandardError |
|---|
| 6 |
end |
|---|
| 7 |
|
|---|
| 8 |
|
|---|
| 9 |
class Variable < String |
|---|
| 10 |
def to_json |
|---|
| 11 |
self |
|---|
| 12 |
end |
|---|
| 13 |
end |
|---|
| 14 |
|
|---|
| 15 |
|
|---|
| 16 |
|
|---|
| 17 |
|
|---|
| 18 |
|
|---|
| 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 |
|---|