Skip to content
This repository
Browse code

Automatically prefer Yajl or JSON backend over Yaml, if available

  • Loading branch information...
commit 63bb955a99eb46e257655c93dd64e86ebbf05651 1 parent a96bf4a
Jeremy Kemper authored February 05, 2010
2  activesupport/CHANGELOG
... ...
@@ -1,6 +1,6 @@
1 1
 *Rails 3.0 (pending)*
2 2
 
3  
-* JSON backend for YAJL.  #2666 [Brian Lopez]
  3
+* JSON backend for YAJL. Preferred if available.  #2666 [Brian Lopez]
4 4
 
5 5
 
6 6
 *Rails 3.0.0 [beta] (February 4, 2010)*
17  activesupport/lib/active_support/json/decoding.rb
@@ -6,12 +6,15 @@ module ActiveSupport
6 6
   mattr_accessor :parse_json_times
7 7
 
8 8
   module JSON
  9
+    # Listed in order of preference.
  10
+    DECODERS = %w(Yajl JSONGem Yaml)
  11
+
9 12
     class << self
10 13
       attr_reader :parse_error
11 14
       delegate :decode, :to => :backend
12 15
 
13 16
       def backend
14  
-        self.backend = "Yaml" unless defined?(@backend)
  17
+        set_default_backend unless defined?(@backend)
15 18
         @backend
16 19
       end
17 20
 
@@ -31,6 +34,18 @@ def with_backend(name)
31 34
       ensure
32 35
         self.backend = old_backend
33 36
       end
  37
+
  38
+      def set_default_backend
  39
+        DECODERS.find do |name|
  40
+          begin
  41
+            self.backend = name
  42
+            true
  43
+          rescue LoadError
  44
+            # Try next decoder.
  45
+            false
  46
+          end
  47
+        end
  48
+      end
34 49
     end
35 50
   end
36 51
 end
2  activesupport/test/json/decoding_test.rb
@@ -45,7 +45,7 @@ class TestJSONDecoding < ActiveSupport::TestCase
45 45
   }
46 46
 
47 47
   # load the default JSON backend
48  
-  ActiveSupport::JSON.backend
  48
+  ActiveSupport::JSON.backend = 'Yaml'
49 49
 
50 50
   backends = %w(Yaml)
51 51
   backends << "JSONGem" if defined?(::JSON)

4 notes on commit 63bb955

Brian Lopez

very nice ;)

Brian Lopez

any chance these would apply cleanly in the 2.3 branch?

Jeremy Kemper
Owner

probably, yes

Bruno Michel
nono commented on 63bb955 March 01, 2010

It should be nice to have the same thing for XmlMini. I wanted to make a patch for it, but I can't run the tests:
*** glibc detected *** /usr/bin/ruby1.8: free(): invalid pointer: 0x00345440 ***

Please sign in to comment.
Something went wrong with that request. Please try again.