Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement custom Marshal encoder/decoder for StripeObject #592

Merged
merged 1 commit into from
Oct 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lib/stripe/stripe_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,28 @@ def dirty!
end
end

# Implements custom encoding for Ruby's Marshal. The data produced by this
# method should be comprehendable by #marshal_load.
#
# This allows us to remove certain features that cannot or should not be
# serialized.
def marshal_dump
# The StripeClient instance in @opts is not serializable and is not
# really a property of the StripeObject, so we exclude it when
# dumping
opts = @opts.clone
opts.delete(:client)
[@values, opts]
end

# Implements custom decoding for Ruby's Marshal. Consumes data that's
# produced by #marshal_dump.
def marshal_load(data)
values, opts = data
initialize(values[:id])
initialize_from(values, opts)
end

def serialize_params(options = {})
update_hash = {}

Expand Down
13 changes: 13 additions & 0 deletions test/stripe/stripe_object_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -410,5 +410,18 @@ class StripeObjectTest < Test::Unit::TestCase
end
assert_match(/\(object\).foo = nil/, e.message)
end

should "marshal and unmarshal using custom encoder and decoder" do
obj = Stripe::StripeObject.construct_from(
{ id: 1, name: "Stripe" },
api_key: "apikey",
client: StripeClient.active_client
)
m = Marshal.load(Marshal.dump(obj))
assert_equal 1, m.id
assert_equal "Stripe", m.name
expected_hash = { api_key: "apikey" }
assert_equal expected_hash, m.instance_variable_get("@opts")
end
end
end