Explorar o código

Merge pull request #107 from Shopify/issue_103

Fix error handling when the API returns just a plain string instead of a hash
Peter Schröder %!s(int64=11) %!d(string=hai) anos
pai
achega
bb351439ee
Modificáronse 2 ficheiros con 36 adicións e 4 borrados
  1. 14 4
      lib/active_resource/json_errors.rb
  2. 22 0
      test/active_resource/json_errors_test.rb

+ 14 - 4
lib/active_resource/json_errors.rb

@@ -2,6 +2,16 @@ require 'active_resource/base'
 
 module ActiveResource
   class Errors < ActiveModel::Errors
+    def from_json(json, save_cache = false)
+      data = ActiveSupport::JSON.decode(json)['errors'] || {} rescue {}
+      case data
+      when String
+        from_string(data, save_cache)
+      else
+        from_hash(data, save_cache)
+      end
+    end
+
     def from_hash(messages, save_cache = false)
       clear unless save_cache
 
@@ -12,10 +22,10 @@ module ActiveResource
       end
     end
 
-    # Grabs errors from a json response.
-    def from_json(json, save_cache = false)
-      hash = ActiveSupport::JSON.decode(json)['errors'] || {} rescue {}
-      from_hash hash, save_cache
+    def from_string(error, save_cache = false)
+      clear unless save_cache
+
+      add("message", error)
     end
   end
 end

+ 22 - 0
test/active_resource/json_errors_test.rb

@@ -0,0 +1,22 @@
+require 'test_helper'
+
+module ActiveResource
+  class JsonErrorsTest < Test::Unit::TestCase
+
+    def test_parsing_of_error_json_hash
+      errors = some_error.from_json({errors: {name: ['missing']}}.to_json)
+      assert_equal({"name"=>["missing"]}, errors)
+    end
+
+    def test_parsing_of_error_json_plain_string
+      errors = some_error.from_json({errors: 'some generic error'}.to_json)
+      assert_equal(["some generic error"], errors)
+    end
+
+    private
+
+    def some_error
+      ActiveResource::Errors.new(ShopifyAPI::Order.new)
+    end
+  end
+end