From f7c4dfa95264d1c5e75ae5614717338ca0152a15 Mon Sep 17 00:00:00 2001 From: ashkan Date: Wed, 25 Oct 2017 15:25:26 -0400 Subject: [PATCH 1/2] Skip calling to_hash for nil --- lib/stripe/stripe_object.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/stripe/stripe_object.rb b/lib/stripe/stripe_object.rb index 183004805..85827ffb8 100644 --- a/lib/stripe/stripe_object.rb +++ b/lib/stripe/stripe_object.rb @@ -116,7 +116,7 @@ def as_json(*a) def to_hash maybe_to_hash = lambda do |value| - value.respond_to?(:to_hash) ? value.to_hash : value + value && value.respond_to?(:to_hash) ? value.to_hash : value end @values.each_with_object({}) do |(key, value), acc| From f04b01ce0a869eaea235249fd2fc4d75ed00607a Mon Sep 17 00:00:00 2001 From: ashkan Date: Fri, 27 Oct 2017 10:36:25 -0400 Subject: [PATCH 2/2] Add test for not calling to_hash on nil --- test/stripe/stripe_object_test.rb | 50 ++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/test/stripe/stripe_object_test.rb b/test/stripe/stripe_object_test.rb index 5e6429f58..a4f86ce23 100644 --- a/test/stripe/stripe_object_test.rb +++ b/test/stripe/stripe_object_test.rb @@ -115,23 +115,39 @@ class TestObject < Stripe::StripeObject; end end end - should "recursively call to_hash on its values" do - # deep nested hash (when contained in an array) or StripeObject - nested_hash = { id: 7, foo: "bar" } - nested = Stripe::StripeObject.construct_from(nested_hash) - - obj = Stripe::StripeObject.construct_from(id: 1, - # simple hash that contains a StripeObject to help us test deep - # recursion - nested: { object: "list", data: [nested] }, - list: [nested]) - - expected_hash = { - id: 1, - nested: { object: "list", data: [nested_hash] }, - list: [nested_hash], - } - assert_equal expected_hash, obj.to_hash + context "#to_hash" do + should "skip calling to_hash on nil" do + module NilWithToHash + def to_hash + raise "Can't call to_hash on nil" + end + end + NilClass.include NilWithToHash + + hash_with_nil = { id: 3, foo: nil } + obj = StripeObject.construct_from(hash_with_nil) + expected_hash = { id: 3, foo: nil } + assert_equal expected_hash, obj.to_hash + end + + should "recursively call to_hash on its values" do + # deep nested hash (when contained in an array) or StripeObject + nested_hash = { id: 7, foo: "bar" } + nested = Stripe::StripeObject.construct_from(nested_hash) + + obj = Stripe::StripeObject.construct_from(id: 1, + # simple hash that contains a StripeObject to help us test deep + # recursion + nested: { object: "list", data: [nested] }, + list: [nested]) + + expected_hash = { + id: 1, + nested: { object: "list", data: [nested_hash] }, + list: [nested_hash], + } + assert_equal expected_hash, obj.to_hash + end end should "assign question mark accessors for booleans" do