Selaa lähdekoodia

Change root json decode patch to patch only 3.0.x versions

Root encode fix now properly limited to ShopifyAPI Base classes
only instead of overwriting Rails module functionality for any
project that includes this gem. Our previous soluction was ignoring
the system-wide include_root_in_json setting that wasn't
explicitly set in the to_json options.
Gareth du Plooy 12 vuotta sitten
vanhempi
commit
7a25f99f86
2 muutettua tiedostoa jossa 25 lisäystä ja 34 poistoa
  1. 11 34
      lib/shopify_api/json_format.rb
  2. 14 0
      lib/shopify_api/resources/base.rb

+ 11 - 34
lib/shopify_api/json_format.rb

@@ -1,39 +1,16 @@
 module ActiveResource
 module ActiveResource
-  class Base
-    def encode(options = {})
-      same = dup
-      same.attributes = {self.class.element_name => same.attributes} if self.class.format.extension == 'json'
-      
-      same.send("to_#{self.class.format.extension}", options)
-    end
-  end
-
-  module Formats
-    module JsonFormat
-      def decode(json)
-        data = ActiveSupport::JSON.decode(json)
-        if data.is_a?(Hash) && data.keys.size == 1
-          data.values.first
-        else
-          data
-        end
-      end
-    end
-  end
-end
-
-module ActiveModel
-  module Serializers
-    module JSON
-      def as_json(options = nil)
-        root = options[:root] if options.try(:key?, :root)
-        if include_root_in_json
-          root = self.class.model_name.element if root == true
-          { root => serializable_hash(options) }
-        else
-          serializable_hash(options)
+  if ActiveResource::VERSION::STRING =~ /^3\.0\./
+    module Formats
+      module JsonFormat
+        def decode(json)
+          data = ActiveSupport::JSON.decode(json)
+          if data.is_a?(Hash) && data.keys.size == 1
+            data.values.first
+          else
+            data
+          end
         end
         end
       end
       end
     end
     end
   end
   end
-end
+end

+ 14 - 0
lib/shopify_api/resources/base.rb

@@ -34,9 +34,23 @@ module ShopifyAPI
       !id.nil?
       !id.nil?
     end
     end
 
 
+    def encode(options = {})
+      obj = dup
+
+      if self.class.format.extension == 'json' && !already_has_root_element?(obj.attributes)
+        obj.attributes = {self.class.element_name => obj.attributes}
+      end
+
+      obj.send("to_#{self.class.format.extension}", options)
+    end
     private
     private
     def only_id
     def only_id
       encode(:only => :id, :include => [], :methods => [])
       encode(:only => :id, :include => [], :methods => [])
     end
     end
+
+    def already_has_root_element?(attributes)
+      attributes.keys.size == 1 && attributes.values.first.kind_of?(Hash)
+    end
   end
   end
 end
 end
+