Skip to content

Commit

Permalink
Merge pull request #625 from stripe/ob-skip-to-hash-for-nil
Browse files Browse the repository at this point in the history
Skip calling to_hash for nil
  • Loading branch information
ob-stripe authored Feb 12, 2018
2 parents f6484e3 + 5f1ddf2 commit 1abb8a5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 18 deletions.
2 changes: 1 addition & 1 deletion lib/stripe/stripe_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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|
Expand Down
51 changes: 34 additions & 17 deletions test/stripe/stripe_object_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,23 +115,40 @@ 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
# include is private in Ruby 2.0
NilClass.send(: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
Expand Down

0 comments on commit 1abb8a5

Please sign in to comment.