Permalink
Browse files

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.
  • Loading branch information...
1 parent a2bd1c6 commit 7a25f99f86ede50269a578f5d78aa7ae35628f9d @garethson garethson committed Sep 28, 2012
Showing with 25 additions and 34 deletions.
  1. +11 −34 lib/shopify_api/json_format.rb
  2. +14 −0 lib/shopify_api/resources/base.rb
View
45 lib/shopify_api/json_format.rb
@@ -1,39 +1,16 @@
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
View
14 lib/shopify_api/resources/base.rb
@@ -34,9 +34,23 @@ def persisted?
!id.nil?
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
def only_id
encode(:only => :id, :include => [], :methods => [])
end
+
+ def already_has_root_element?(attributes)
+ attributes.keys.size == 1 && attributes.values.first.kind_of?(Hash)
+ end
end
end
+

0 comments on commit 7a25f99

Please sign in to comment.