stripe 3.2.0 → 5.16.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (230) hide show
  1. checksums.yaml +5 -5
  2. data/.editorconfig +10 -0
  3. data/.gitignore +3 -0
  4. data/.rubocop.yml +80 -0
  5. data/.rubocop_todo.yml +33 -0
  6. data/.travis.yml +9 -7
  7. data/.vscode/extensions.json +7 -0
  8. data/.vscode/settings.json +8 -0
  9. data/CHANGELOG.md +876 -0
  10. data/CODE_OF_CONDUCT.md +77 -0
  11. data/Gemfile +21 -21
  12. data/History.txt +1 -678
  13. data/README.md +195 -53
  14. data/Rakefile +18 -12
  15. data/VERSION +1 -1
  16. data/bin/stripe-console +5 -3
  17. data/lib/stripe/api_operations/create.rb +3 -1
  18. data/lib/stripe/api_operations/delete.rb +26 -2
  19. data/lib/stripe/api_operations/list.rb +3 -12
  20. data/lib/stripe/api_operations/nested_resource.rb +72 -0
  21. data/lib/stripe/api_operations/request.rb +33 -15
  22. data/lib/stripe/api_operations/save.rb +18 -9
  23. data/lib/stripe/api_resource.rb +60 -10
  24. data/lib/stripe/connection_manager.rb +159 -0
  25. data/lib/stripe/error_object.rb +94 -0
  26. data/lib/stripe/errors.rb +39 -19
  27. data/lib/stripe/instrumentation.rb +82 -0
  28. data/lib/stripe/list_object.rb +54 -22
  29. data/lib/stripe/multipart_encoder.rb +131 -0
  30. data/lib/stripe/oauth.rb +22 -14
  31. data/lib/stripe/object_types.rb +96 -0
  32. data/lib/stripe/{account.rb → resources/account.rb} +72 -34
  33. data/lib/stripe/resources/account_link.rb +9 -0
  34. data/lib/stripe/resources/alipay_account.rb +34 -0
  35. data/lib/stripe/{apple_pay_domain.rb → resources/apple_pay_domain.rb} +4 -2
  36. data/lib/stripe/resources/application_fee.rb +13 -0
  37. data/lib/stripe/resources/application_fee_refund.rb +30 -0
  38. data/lib/stripe/{balance.rb → resources/balance.rb} +3 -1
  39. data/lib/stripe/{balance_transaction.rb → resources/balance_transaction.rb} +3 -5
  40. data/lib/stripe/resources/bank_account.rb +42 -0
  41. data/lib/stripe/{bitcoin_receiver.rb → resources/bitcoin_receiver.rb} +6 -5
  42. data/lib/stripe/resources/bitcoin_transaction.rb +15 -0
  43. data/lib/stripe/resources/capability.rb +33 -0
  44. data/lib/stripe/resources/card.rb +37 -0
  45. data/lib/stripe/resources/charge.rb +22 -0
  46. data/lib/stripe/resources/checkout/session.rb +12 -0
  47. data/lib/stripe/{country_spec.rb → resources/country_spec.rb} +3 -5
  48. data/lib/stripe/{coupon.rb → resources/coupon.rb} +4 -2
  49. data/lib/stripe/resources/credit_note.rb +32 -0
  50. data/lib/stripe/resources/credit_note_line_item.rb +7 -0
  51. data/lib/stripe/resources/customer.rb +35 -0
  52. data/lib/stripe/resources/customer_balance_transaction.rb +30 -0
  53. data/lib/stripe/resources/discount.rb +7 -0
  54. data/lib/stripe/resources/dispute.rb +21 -0
  55. data/lib/stripe/resources/ephemeral_key.rb +19 -0
  56. data/lib/stripe/{event.rb → resources/event.rb} +3 -1
  57. data/lib/stripe/resources/exchange_rate.rb +9 -0
  58. data/lib/stripe/resources/file.rb +34 -0
  59. data/lib/stripe/resources/file_link.rb +11 -0
  60. data/lib/stripe/resources/invoice.rb +73 -0
  61. data/lib/stripe/{invoice_item.rb → resources/invoice_item.rb} +4 -2
  62. data/lib/stripe/{invoice_line_item.rb → resources/invoice_line_item.rb} +3 -1
  63. data/lib/stripe/resources/issuing/authorization.rb +33 -0
  64. data/lib/stripe/resources/issuing/card.rb +24 -0
  65. data/lib/stripe/resources/issuing/card_details.rb +9 -0
  66. data/lib/stripe/resources/issuing/cardholder.rb +13 -0
  67. data/lib/stripe/resources/issuing/dispute.rb +13 -0
  68. data/lib/stripe/resources/issuing/transaction.rb +12 -0
  69. data/lib/stripe/resources/login_link.rb +14 -0
  70. data/lib/stripe/resources/mandate.rb +7 -0
  71. data/lib/stripe/resources/order.rb +32 -0
  72. data/lib/stripe/{order_return.rb → resources/order_return.rb} +3 -5
  73. data/lib/stripe/resources/payment_intent.rb +42 -0
  74. data/lib/stripe/resources/payment_method.rb +32 -0
  75. data/lib/stripe/resources/payout.rb +22 -0
  76. data/lib/stripe/resources/person.rb +31 -0
  77. data/lib/stripe/{plan.rb → resources/plan.rb} +3 -1
  78. data/lib/stripe/{product.rb → resources/product.rb} +5 -3
  79. data/lib/stripe/resources/radar/early_fraud_warning.rb +11 -0
  80. data/lib/stripe/resources/radar/value_list.rb +14 -0
  81. data/lib/stripe/resources/radar/value_list_item.rb +13 -0
  82. data/lib/stripe/{recipient.rb → resources/recipient.rb} +5 -6
  83. data/lib/stripe/resources/recipient_transfer.rb +7 -0
  84. data/lib/stripe/{refund.rb → resources/refund.rb} +3 -1
  85. data/lib/stripe/resources/reporting/report_run.rb +12 -0
  86. data/lib/stripe/resources/reporting/report_type.rb +12 -0
  87. data/lib/stripe/resources/reversal.rb +29 -0
  88. data/lib/stripe/resources/review.rb +20 -0
  89. data/lib/stripe/resources/setup_intent.rb +32 -0
  90. data/lib/stripe/resources/sigma/scheduled_query_run.rb +15 -0
  91. data/lib/stripe/{sku.rb → resources/sku.rb} +5 -3
  92. data/lib/stripe/resources/source.rb +46 -0
  93. data/lib/stripe/resources/source_transaction.rb +7 -0
  94. data/lib/stripe/resources/subscription.rb +25 -0
  95. data/lib/stripe/resources/subscription_item.rb +25 -0
  96. data/lib/stripe/resources/subscription_schedule.rb +32 -0
  97. data/lib/stripe/resources/tax_id.rb +26 -0
  98. data/lib/stripe/resources/tax_rate.rb +11 -0
  99. data/lib/stripe/resources/terminal/connection_token.rb +11 -0
  100. data/lib/stripe/resources/terminal/location.rb +14 -0
  101. data/lib/stripe/resources/terminal/reader.rb +14 -0
  102. data/lib/stripe/{three_d_secure.rb → resources/three_d_secure.rb} +3 -1
  103. data/lib/stripe/{token.rb → resources/token.rb} +3 -1
  104. data/lib/stripe/resources/topup.rb +22 -0
  105. data/lib/stripe/resources/transfer.rb +26 -0
  106. data/lib/stripe/resources/usage_record.rb +7 -0
  107. data/lib/stripe/resources/usage_record_summary.rb +7 -0
  108. data/lib/stripe/resources/webhook_endpoint.rb +12 -0
  109. data/lib/stripe/resources.rb +79 -0
  110. data/lib/stripe/singleton_api_resource.rb +10 -4
  111. data/lib/stripe/stripe_client.rb +658 -337
  112. data/lib/stripe/stripe_object.rb +248 -126
  113. data/lib/stripe/stripe_response.rb +55 -21
  114. data/lib/stripe/util.rb +145 -187
  115. data/lib/stripe/version.rb +3 -1
  116. data/lib/stripe/webhook.rb +27 -16
  117. data/lib/stripe.rb +139 -90
  118. data/stripe.gemspec +26 -14
  119. data/test/openapi/README.md +9 -0
  120. data/test/stripe/account_link_test.rb +18 -0
  121. data/test/stripe/account_test.rb +311 -101
  122. data/test/stripe/alipay_account_test.rb +21 -1
  123. data/test/stripe/api_operations_test.rb +57 -8
  124. data/test/stripe/api_resource_test.rb +359 -271
  125. data/test/stripe/apple_pay_domain_test.rb +26 -11
  126. data/test/stripe/application_fee_refund_test.rb +10 -8
  127. data/test/stripe/application_fee_test.rb +49 -3
  128. data/test/stripe/balance_test.rb +4 -2
  129. data/test/stripe/balance_transaction_test.rb +20 -0
  130. data/test/stripe/bank_account_test.rb +11 -11
  131. data/test/stripe/capability_test.rb +45 -0
  132. data/test/stripe/charge_test.rb +25 -18
  133. data/test/stripe/checkout/session_test.rb +41 -0
  134. data/test/stripe/connection_manager_test.rb +163 -0
  135. data/test/stripe/country_spec_test.rb +6 -4
  136. data/test/stripe/coupon_test.rb +29 -10
  137. data/test/stripe/credit_note_test.rb +90 -0
  138. data/test/stripe/customer_balance_transaction_test.rb +37 -0
  139. data/test/stripe/customer_card_test.rb +13 -17
  140. data/test/stripe/customer_test.rb +161 -49
  141. data/test/stripe/dispute_test.rb +19 -8
  142. data/test/stripe/ephemeral_key_test.rb +23 -14
  143. data/test/stripe/errors_test.rb +32 -9
  144. data/test/stripe/exchange_rate_test.rb +20 -0
  145. data/test/stripe/file_link_test.rb +41 -0
  146. data/test/stripe/file_test.rb +87 -0
  147. data/test/stripe/instrumentation_test.rb +74 -0
  148. data/test/stripe/invoice_item_test.rb +31 -18
  149. data/test/stripe/invoice_line_item_test.rb +3 -1
  150. data/test/stripe/invoice_test.rb +158 -39
  151. data/test/stripe/issuing/authorization_test.rb +72 -0
  152. data/test/stripe/issuing/card_test.rb +62 -0
  153. data/test/stripe/issuing/cardholder_test.rb +53 -0
  154. data/test/stripe/issuing/dispute_test.rb +45 -0
  155. data/test/stripe/issuing/transaction_test.rb +48 -0
  156. data/test/stripe/list_object_test.rb +120 -88
  157. data/test/stripe/login_link_test.rb +16 -14
  158. data/test/stripe/mandate_test.rb +14 -0
  159. data/test/stripe/multipart_encoder_test.rb +130 -0
  160. data/test/stripe/oauth_test.rb +69 -50
  161. data/test/stripe/order_return_test.rb +7 -5
  162. data/test/stripe/order_test.rb +39 -14
  163. data/test/stripe/payment_intent_test.rb +107 -0
  164. data/test/stripe/payment_method_test.rb +84 -0
  165. data/test/stripe/payout_test.rb +18 -9
  166. data/test/stripe/person_test.rb +46 -0
  167. data/test/stripe/plan_test.rb +67 -19
  168. data/test/stripe/product_test.rb +28 -14
  169. data/test/stripe/radar/early_fraud_warning_test.rb +22 -0
  170. data/test/stripe/radar/value_list_item_test.rb +48 -0
  171. data/test/stripe/radar/value_list_test.rb +61 -0
  172. data/test/stripe/recipient_test.rb +27 -13
  173. data/test/stripe/refund_test.rb +11 -9
  174. data/test/stripe/reporting/report_run_test.rb +33 -0
  175. data/test/stripe/reporting/report_type_test.rb +22 -0
  176. data/test/stripe/reversal_test.rb +12 -10
  177. data/test/stripe/review_test.rb +27 -0
  178. data/test/stripe/setup_intent_test.rb +84 -0
  179. data/test/stripe/sigma/scheduled_query_run_test.rb +22 -0
  180. data/test/stripe/sku_test.rb +24 -12
  181. data/test/stripe/source_test.rb +70 -19
  182. data/test/stripe/stripe_client_test.rb +867 -326
  183. data/test/stripe/stripe_object_test.rb +284 -182
  184. data/test/stripe/stripe_response_test.rb +73 -24
  185. data/test/stripe/subscription_item_test.rb +47 -15
  186. data/test/stripe/subscription_schedule_test.rb +82 -0
  187. data/test/stripe/subscription_test.rb +41 -19
  188. data/test/stripe/tax_id_test.rb +31 -0
  189. data/test/stripe/tax_rate_test.rb +43 -0
  190. data/test/stripe/terminal/connection_token_test.rb +16 -0
  191. data/test/stripe/terminal/location_test.rb +68 -0
  192. data/test/stripe/terminal/reader_test.rb +62 -0
  193. data/test/stripe/three_d_secure_test.rb +4 -2
  194. data/test/stripe/topup_test.rb +62 -0
  195. data/test/stripe/transfer_test.rb +55 -8
  196. data/test/stripe/usage_record_summary_test.rb +29 -0
  197. data/test/stripe/util_test.rb +173 -84
  198. data/test/stripe/webhook_endpoint_test.rb +59 -0
  199. data/test/stripe/webhook_test.rb +21 -17
  200. data/test/stripe_mock.rb +78 -0
  201. data/test/stripe_test.rb +6 -15
  202. data/test/test_data.rb +28 -26
  203. data/test/test_helper.rb +48 -29
  204. metadata +183 -70
  205. data/lib/stripe/alipay_account.rb +0 -22
  206. data/lib/stripe/application_fee.rb +0 -22
  207. data/lib/stripe/application_fee_refund.rb +0 -20
  208. data/lib/stripe/bank_account.rb +0 -30
  209. data/lib/stripe/bitcoin_transaction.rb +0 -11
  210. data/lib/stripe/card.rb +0 -27
  211. data/lib/stripe/charge.rb +0 -82
  212. data/lib/stripe/customer.rb +0 -79
  213. data/lib/stripe/dispute.rb +0 -17
  214. data/lib/stripe/ephemeral_key.rb +0 -18
  215. data/lib/stripe/file_upload.rb +0 -33
  216. data/lib/stripe/invoice.rb +0 -29
  217. data/lib/stripe/login_link.rb +0 -9
  218. data/lib/stripe/order.rb +0 -29
  219. data/lib/stripe/payout.rb +0 -18
  220. data/lib/stripe/recipient_transfer.rb +0 -6
  221. data/lib/stripe/reversal.rb +0 -20
  222. data/lib/stripe/source.rb +0 -23
  223. data/lib/stripe/subscription.rb +0 -33
  224. data/lib/stripe/subscription_item.rb +0 -14
  225. data/lib/stripe/transfer.rb +0 -18
  226. data/test/api_stub_helpers.rb +0 -0
  227. data/test/stripe/bitcoin_receiver_test.rb +0 -67
  228. data/test/stripe/bitcoin_transaction_test.rb +0 -19
  229. data/test/stripe/file_upload_test.rb +0 -66
  230. data/test/stripe/recipient_card_test.rb +0 -44
@@ -1,15 +1,76 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
4
  class StripeObject
3
5
  include Enumerable
4
6
 
5
- @@permanent_attributes = Set.new([:id])
7
+ @@permanent_attributes = Set.new([:id]) # rubocop:disable Style/ClassVars
6
8
 
7
9
  # The default :id method is deprecated and isn't useful to us
8
- if method_defined?(:id)
9
- undef :id
10
+ undef :id if method_defined?(:id)
11
+
12
+ # Sets the given parameter name to one which is known to be an additive
13
+ # object.
14
+ #
15
+ # Additive objects are subobjects in the API that don't have the same
16
+ # semantics as most subobjects, which are fully replaced when they're set.
17
+ # This is best illustrated by example. The `source` parameter sent when
18
+ # updating a subscription is *not* additive; if we set it:
19
+ #
20
+ # source[object]=card&source[number]=123
21
+ #
22
+ # We expect the old `source` object to have been overwritten completely. If
23
+ # the previous source had an `address_state` key associated with it and we
24
+ # didn't send one this time, that value of `address_state` is gone.
25
+ #
26
+ # By contrast, additive objects are those that will have new data added to
27
+ # them while keeping any existing data in place. The only known case of its
28
+ # use is for `metadata`, but it could in theory be more general. As an
29
+ # example, say we have a `metadata` object that looks like this on the
30
+ # server side:
31
+ #
32
+ # metadata = { old: "old_value" }
33
+ #
34
+ # If we update the object with `metadata[new]=new_value`, the server side
35
+ # object now has *both* fields:
36
+ #
37
+ # metadata = { old: "old_value", new: "new_value" }
38
+ #
39
+ # This is okay in itself because usually users will want to treat it as
40
+ # additive:
41
+ #
42
+ # obj.metadata[:new] = "new_value"
43
+ # obj.save
44
+ #
45
+ # However, in other cases, they may want to replace the entire existing
46
+ # contents:
47
+ #
48
+ # obj.metadata = { new: "new_value" }
49
+ # obj.save
50
+ #
51
+ # This is where things get a little bit tricky because in order to clear
52
+ # any old keys that may have existed, we actually have to send an explicit
53
+ # empty string to the server. So the operation above would have to send
54
+ # this form to get the intended behavior:
55
+ #
56
+ # metadata[old]=&metadata[new]=new_value
57
+ #
58
+ # This method allows us to track which parameters are considered additive,
59
+ # and lets us behave correctly where appropriate when serializing
60
+ # parameters to be sent.
61
+ def self.additive_object_param(name)
62
+ @additive_params ||= Set.new
63
+ @additive_params << name
64
+ end
65
+
66
+ # Returns whether the given name is an additive object parameter. See
67
+ # `.additive_object_param` for details.
68
+ def self.additive_object_param?(name)
69
+ @additive_params ||= Set.new
70
+ @additive_params.include?(name)
10
71
  end
11
72
 
12
- def initialize(id=nil, opts={})
73
+ def initialize(id = nil, opts = {})
13
74
  id, @retrieve_params = Util.normalize_id(id)
14
75
  @opts = Util.normalize_opts(opts)
15
76
  @original_values = {}
@@ -21,18 +82,32 @@ module Stripe
21
82
  @values[:id] = id if id
22
83
  end
23
84
 
24
- def self.construct_from(values, opts={})
85
+ def self.construct_from(values, opts = {})
25
86
  values = Stripe::Util.symbolize_names(values)
26
87
 
27
88
  # work around protected #initialize_from for now
28
- self.new(values[:id]).send(:initialize_from, values, opts)
89
+ new(values[:id]).send(:initialize_from, values, opts)
29
90
  end
30
91
 
31
92
  # Determines the equality of two Stripe objects. Stripe objects are
32
93
  # considered to be equal if they have the same set of values and each one
33
94
  # of those values is the same.
34
95
  def ==(other)
35
- other.is_a?(StripeObject) && @values == other.instance_variable_get(:@values)
96
+ other.is_a?(StripeObject) &&
97
+ @values == other.instance_variable_get(:@values)
98
+ end
99
+
100
+ # Hash equality. As with `#==`, we consider two equivalent Stripe objects
101
+ # equal.
102
+ def eql?(other)
103
+ # Defer to the implementation on `#==`.
104
+ self == other
105
+ end
106
+
107
+ # As with equality in `#==` and `#eql?`, we hash two Stripe objects to the
108
+ # same value if they're equivalent objects.
109
+ def hash
110
+ @values.hash
36
111
  end
37
112
 
38
113
  # Indicates whether or not the resource has been deleted on the server.
@@ -42,26 +117,15 @@ module Stripe
42
117
  @values.fetch(:deleted, false)
43
118
  end
44
119
 
45
- def to_s(*args)
120
+ def to_s(*_args)
46
121
  JSON.pretty_generate(to_hash)
47
122
  end
48
123
 
49
124
  def inspect
50
- id_string = (self.respond_to?(:id) && !self.id.nil?) ? " id=#{self.id}" : ""
51
- "#<#{self.class}:0x#{self.object_id.to_s(16)}#{id_string}> JSON: " + JSON.pretty_generate(@values)
52
- end
53
-
54
- # Re-initializes the object based on a hash of values (usually one that's
55
- # come back from an API call). Adds or removes value accessors as necessary
56
- # and updates the state of internal data.
57
- #
58
- # Please don't use this method. If you're trying to do mass assignment, try
59
- # #initialize_from instead.
60
- def refresh_from(values, opts, partial=false)
61
- initialize_from(values, opts, partial)
125
+ id_string = respond_to?(:id) && !id.nil? ? " id=#{id}" : ""
126
+ "#<#{self.class}:0x#{object_id.to_s(16)}#{id_string}> JSON: " +
127
+ JSON.pretty_generate(@values)
62
128
  end
63
- extend Gem::Deprecate
64
- deprecate :refresh_from, "#update_attributes", 2016, 01
65
129
 
66
130
  # Mass assigns attributes on the model.
67
131
  #
@@ -71,7 +135,8 @@ module Stripe
71
135
  # ==== Attributes
72
136
  #
73
137
  # * +values+ - Hash of values to use to update the current attributes of
74
- # the object.
138
+ # the object. If you are on ruby 2.7 or higher make sure to wrap in curly
139
+ # braces to be ruby 3 compatible.
75
140
  # * +opts+ - Options for +StripeObject+ like an API key that will be reused
76
141
  # on subsequent API calls.
77
142
  #
@@ -80,10 +145,7 @@ module Stripe
80
145
  # * +:dirty+ - Whether values should be initiated as "dirty" (unsaved) and
81
146
  # which applies only to new StripeObjects being initiated under this
82
147
  # StripeObject. Defaults to true.
83
- def update_attributes(values, opts = {}, method_options = {})
84
- # Default to true. TODO: Convert to optional arguments after we're off
85
- # 1.9 which will make this quite a bit more clear.
86
- dirty = method_options.fetch(:dirty, true)
148
+ def update_attributes(values, opts = {}, dirty: true)
87
149
  values.each do |k, v|
88
150
  add_accessors([k], values) unless metaclass.method_defined?(k.to_sym)
89
151
  @values[k] = Util.convert_to_stripe_object(v, opts)
@@ -92,12 +154,12 @@ module Stripe
92
154
  end
93
155
  end
94
156
 
95
- def [](k)
96
- @values[k.to_sym]
157
+ def [](key)
158
+ @values[key.to_sym]
97
159
  end
98
160
 
99
- def []=(k, v)
100
- send(:"#{k}=", v)
161
+ def []=(key, value)
162
+ send(:"#{key}=", value)
101
163
  end
102
164
 
103
165
  def keys
@@ -108,27 +170,29 @@ module Stripe
108
170
  @values.values
109
171
  end
110
172
 
111
- def to_json(*a)
173
+ def to_json(*_opts)
174
+ # TODO: pass opts to JSON.generate?
112
175
  JSON.generate(@values)
113
176
  end
114
177
 
115
- def as_json(*a)
116
- @values.as_json(*a)
178
+ def as_json(*opts)
179
+ @values.as_json(*opts)
117
180
  end
118
181
 
119
182
  def to_hash
120
183
  maybe_to_hash = lambda do |value|
184
+ return nil if value.nil?
185
+
121
186
  value.respond_to?(:to_hash) ? value.to_hash : value
122
187
  end
123
188
 
124
- @values.inject({}) do |acc, (key, value)|
189
+ @values.each_with_object({}) do |(key, value), acc|
125
190
  acc[key] = case value
126
191
  when Array
127
192
  value.map(&maybe_to_hash)
128
193
  else
129
194
  maybe_to_hash.call(value)
130
195
  end
131
- acc
132
196
  end
133
197
  end
134
198
 
@@ -136,31 +200,39 @@ module Stripe
136
200
  @values.each(&blk)
137
201
  end
138
202
 
139
- def _dump(level)
140
- # The StripeClient instance in @opts is not serializable and is not
141
- # really a property of the StripeObject, so we exclude it when
142
- # dumping
143
- opts = @opts.clone
144
- opts.delete(:client)
145
- Marshal.dump([@values, opts])
146
- end
147
-
148
- def self._load(args)
149
- values, opts = Marshal.load(args)
150
- construct_from(values, opts)
151
- end
152
-
153
203
  # Sets all keys within the StripeObject as unsaved so that they will be
154
204
  # included with an update when #serialize_params is called. This method is
155
205
  # also recursive, so any StripeObjects contained as values or which are
156
206
  # values in a tenant array are also marked as dirty.
157
207
  def dirty!
158
208
  @unsaved_values = Set.new(@values.keys)
159
- @values.each do |k, v|
209
+ @values.each_value do |v|
160
210
  dirty_value!(v)
161
211
  end
162
212
  end
163
213
 
214
+ # Implements custom encoding for Ruby's Marshal. The data produced by this
215
+ # method should be comprehendable by #marshal_load.
216
+ #
217
+ # This allows us to remove certain features that cannot or should not be
218
+ # serialized.
219
+ def marshal_dump
220
+ # The StripeClient instance in @opts is not serializable and is not
221
+ # really a property of the StripeObject, so we exclude it when
222
+ # dumping
223
+ opts = @opts.clone
224
+ opts.delete(:client)
225
+ [@values, opts]
226
+ end
227
+
228
+ # Implements custom decoding for Ruby's Marshal. Consumes data that's
229
+ # produced by #marshal_dump.
230
+ def marshal_load(data)
231
+ values, opts = data
232
+ initialize(values[:id])
233
+ initialize_from(values, opts)
234
+ end
235
+
164
236
  def serialize_params(options = {})
165
237
  update_hash = {}
166
238
 
@@ -174,31 +246,20 @@ module Stripe
174
246
  # values within in that its parent StripeObject doesn't know about.
175
247
  #
176
248
  unsaved = @unsaved_values.include?(k)
177
- if options[:force] || unsaved || v.is_a?(StripeObject)
178
- update_hash[k.to_sym] =
179
- serialize_params_value(@values[k], @original_values[k], unsaved, options[:force], key: k)
180
- end
249
+ next unless options[:force] || unsaved || v.is_a?(StripeObject)
250
+
251
+ update_hash[k.to_sym] = serialize_params_value(
252
+ @values[k], @original_values[k], unsaved, options[:force], key: k
253
+ )
181
254
  end
182
255
 
183
256
  # a `nil` that makes it out of `#serialize_params_value` signals an empty
184
257
  # value that we shouldn't appear in the serialized form of the object
185
- update_hash.reject! { |_, v| v == nil }
258
+ update_hash.reject! { |_, v| v.nil? }
186
259
 
187
260
  update_hash
188
261
  end
189
262
 
190
- class << self
191
- # This class method has been deprecated in favor of the instance method
192
- # of the same name.
193
- def serialize_params(obj, options = {})
194
- obj.serialize_params(options)
195
- end
196
- extend Gem::Deprecate
197
- deprecate :serialize_params, "#serialize_params", 2016, 9
198
- end
199
-
200
- protected
201
-
202
263
  # A protected field is one that doesn't get an accessor assigned to it
203
264
  # (i.e. `obj.public = ...`) and one which is not allowed to be updated via
204
265
  # the class level `Model.update(id, { ... })`.
@@ -206,11 +267,11 @@ module Stripe
206
267
  []
207
268
  end
208
269
 
209
- def metaclass
270
+ protected def metaclass
210
271
  class << self; self; end
211
272
  end
212
273
 
213
- def remove_accessors(keys)
274
+ protected def remove_accessors(keys)
214
275
  # not available in the #instance_eval below
215
276
  protected_fields = self.class.protected_fields
216
277
 
@@ -221,15 +282,31 @@ module Stripe
221
282
 
222
283
  # Remove methods for the accessor's reader and writer.
223
284
  [k, :"#{k}=", :"#{k}?"].each do |method_name|
224
- if method_defined?(method_name)
285
+ next unless method_defined?(method_name)
286
+
287
+ begin
225
288
  remove_method(method_name)
289
+ rescue NameError
290
+ # In some cases there can be a method that's detected with
291
+ # `method_defined?`, but which cannot be removed with
292
+ # `remove_method`, even though it's on the same class. The only
293
+ # case so far that we've noticed this is when a class is
294
+ # reopened for monkey patching:
295
+ #
296
+ # https://github.com/stripe/stripe-ruby/issues/749
297
+ #
298
+ # Here we swallow that error and issue a warning so at least
299
+ # the program doesn't crash.
300
+ warn("WARNING: Unable to remove method `#{method_name}`; " \
301
+ "if custom, please consider renaming to a name that doesn't " \
302
+ "collide with an API property name.")
226
303
  end
227
304
  end
228
305
  end
229
306
  end
230
307
  end
231
308
 
232
- def add_accessors(keys, values)
309
+ protected def add_accessors(keys, values)
233
310
  # not available in the #instance_eval below
234
311
  protected_fields = self.class.protected_fields
235
312
 
@@ -238,13 +315,21 @@ module Stripe
238
315
  next if protected_fields.include?(k)
239
316
  next if @@permanent_attributes.include?(k)
240
317
 
241
- define_method(k) { @values[k] }
318
+ if k == :method
319
+ # Object#method is a built-in Ruby method that accepts a symbol
320
+ # and returns the corresponding Method object. Because the API may
321
+ # also use `method` as a field name, we check the arity of *args
322
+ # to decide whether to act as a getter or call the parent method.
323
+ define_method(k) { |*args| args.empty? ? @values[k] : super(*args) }
324
+ else
325
+ define_method(k) { @values[k] }
326
+ end
327
+
242
328
  define_method(:"#{k}=") do |v|
243
329
  if v == ""
244
- raise ArgumentError.new(
245
- "You cannot set #{k} to an empty string. " \
330
+ raise ArgumentError, "You cannot set #{k} to an empty string. " \
246
331
  "We interpret empty strings as nil in requests. " \
247
- "You may set (object).#{k} = nil to delete the property.")
332
+ "You may set (object).#{k} = nil to delete the property."
248
333
  end
249
334
  @values[k] = Util.convert_to_stripe_object(v, @opts)
250
335
  dirty_value!(@values[k])
@@ -258,9 +343,13 @@ module Stripe
258
343
  end
259
344
  end
260
345
 
261
- def method_missing(name, *args)
346
+ # Disabling the cop because it's confused by the fact that the methods are
347
+ # protected, but we do define `#respond_to_missing?` just below. Hopefully
348
+ # this is fixed in more recent Rubocop versions.
349
+ # rubocop:disable Style/MissingRespondToMissing
350
+ protected def method_missing(name, *args)
262
351
  # TODO: only allow setting in updateable classes.
263
- if name.to_s.end_with?('=')
352
+ if name.to_s.end_with?("=")
264
353
  attr = name.to_s[0...-1].to_sym
265
354
 
266
355
  # Pull out the assigned value. This is only used in the case of a
@@ -269,31 +358,40 @@ module Stripe
269
358
  val = args.first
270
359
 
271
360
  # the second argument is only required when adding boolean accessors
272
- add_accessors([attr], { attr => val })
361
+ add_accessors([attr], attr => val)
273
362
 
274
363
  begin
275
364
  mth = method(name)
276
365
  rescue NameError
277
- raise NoMethodError.new("Cannot set #{attr} on this object. HINT: you can't set: #{@@permanent_attributes.to_a.join(', ')}")
366
+ raise NoMethodError,
367
+ "Cannot set #{attr} on this object. HINT: you can't set: " \
368
+ "#{@@permanent_attributes.to_a.join(', ')}"
278
369
  end
279
370
  return mth.call(args[0])
280
- else
281
- return @values[name] if @values.has_key?(name)
371
+ elsif @values.key?(name)
372
+ return @values[name]
282
373
  end
283
374
 
284
375
  begin
285
376
  super
286
377
  rescue NoMethodError => e
287
- if @transient_values.include?(name)
288
- raise NoMethodError.new(e.message + ". HINT: The '#{name}' attribute was set in the past, however. It was then wiped when refreshing the object with the result returned by Stripe's API, probably as a result of a save(). The attributes currently available on this object are: #{@values.keys.join(', ')}")
289
- else
290
- raise
291
- end
378
+ # If we notice the accessed name if our set of transient values we can
379
+ # give the user a slightly more helpful error message. If not, just
380
+ # raise right away.
381
+ raise unless @transient_values.include?(name)
382
+
383
+ raise NoMethodError,
384
+ e.message + ". HINT: The '#{name}' attribute was set in the " \
385
+ "past, however. It was then wiped when refreshing the object " \
386
+ "with the result returned by Stripe's API, probably as a " \
387
+ "result of a save(). The attributes currently available on " \
388
+ "this object are: #{@values.keys.join(', ')}"
292
389
  end
293
390
  end
391
+ # rubocop:enable Style/MissingRespondToMissing
294
392
 
295
- def respond_to_missing?(symbol, include_private = false)
296
- @values && @values.has_key?(symbol) || super
393
+ protected def respond_to_missing?(symbol, include_private = false)
394
+ @values && @values.key?(symbol) || super
297
395
  end
298
396
 
299
397
  # Re-initializes the object based on a hash of values (usually one that's
@@ -308,16 +406,18 @@ module Stripe
308
406
  # * +:opts:+ Options for StripeObject like an API key.
309
407
  # * +:partial:+ Indicates that the re-initialization should not attempt to
310
408
  # remove accessors.
311
- def initialize_from(values, opts, partial=false)
409
+ protected def initialize_from(values, opts, partial = false)
312
410
  @opts = Util.normalize_opts(opts)
313
- @original_values = Marshal.load(Marshal.dump(values)) # deep copy
411
+
412
+ # the `#send` is here so that we can keep this method private
413
+ @original_values = self.class.send(:deep_copy, values)
314
414
 
315
415
  removed = partial ? Set.new : Set.new(@values.keys - values.keys)
316
416
  added = Set.new(values.keys - @values.keys)
317
417
 
318
418
  # Wipe old state before setting new. This is useful for e.g. updating a
319
- # customer, where there is no persistent card parameter. Mark those values
320
- # which don't persist as transient
419
+ # customer, where there is no persistent card parameter. Mark those
420
+ # values which don't persist as transient
321
421
 
322
422
  remove_accessors(removed)
323
423
  add_accessors(added, values)
@@ -328,8 +428,8 @@ module Stripe
328
428
  @unsaved_values.delete(k)
329
429
  end
330
430
 
331
- update_attributes(values, opts, :dirty => false)
332
- values.each do |k, _|
431
+ update_attributes(values, opts, dirty: false)
432
+ values.each_key do |k|
333
433
  @transient_values.delete(k)
334
434
  @unsaved_values.delete(k)
335
435
  end
@@ -337,10 +437,10 @@ module Stripe
337
437
  self
338
438
  end
339
439
 
340
- def serialize_params_value(value, original, unsaved, force, key: nil)
341
- case true
342
- when value == nil
343
- ''
440
+ protected def serialize_params_value(value, original, unsaved, force,
441
+ key: nil)
442
+ if value.nil?
443
+ ""
344
444
 
345
445
  # The logic here is that essentially any object embedded in another
346
446
  # object that had a `type` is actually an API resource of a different
@@ -364,10 +464,10 @@ module Stripe
364
464
  # We throw an error if a property was set explicitly but we can't do
365
465
  # anything with it because the integration is probably not working as the
366
466
  # user intended it to.
367
- when value.is_a?(APIResource) && !value.save_with_parent
467
+ elsif value.is_a?(APIResource) && !value.save_with_parent
368
468
  if !unsaved
369
469
  nil
370
- elsif value.respond_to?(:id) && value.id != nil
470
+ elsif value.respond_to?(:id) && !value.id.nil?
371
471
  value
372
472
  else
373
473
  raise ArgumentError, "Cannot save property `#{key}` containing " \
@@ -375,15 +475,11 @@ module Stripe
375
475
  "not marked as `save_with_parent`."
376
476
  end
377
477
 
378
- when value.is_a?(Array)
478
+ elsif value.is_a?(Array)
379
479
  update = value.map { |v| serialize_params_value(v, nil, true, force) }
380
480
 
381
481
  # This prevents an array that's unchanged from being resent.
382
- if update != serialize_params_value(original, nil, true, force)
383
- update
384
- else
385
- nil
386
- end
482
+ update if update != serialize_params_value(original, nil, true, force)
387
483
 
388
484
  # Handle a Hash for now, but in the long run we should be able to
389
485
  # eliminate all places where hashes are stored as values internally by
@@ -395,16 +491,20 @@ module Stripe
395
491
  # existing array being held by a StripeObject. This could happen for
396
492
  # example by appending a new hash onto `additional_owners` for an
397
493
  # account.
398
- when value.is_a?(Hash)
494
+ elsif value.is_a?(Hash)
399
495
  Util.convert_to_stripe_object(value, @opts).serialize_params
400
496
 
401
- when value.is_a?(StripeObject)
402
- update = value.serialize_params(:force => force)
497
+ elsif value.is_a?(StripeObject)
498
+ update = value.serialize_params(force: force)
403
499
 
404
- # If the entire object was replaced, then we need blank each field of
405
- # the old object that held a value. The new serialized values will
406
- # override any of these empty values.
407
- update = empty_values(original).merge(update) if original && unsaved
500
+ # If the entire object was replaced and this is an additive object,
501
+ # then we need blank each field of the old object that held a value
502
+ # because otherwise the update to the keys of the object will be
503
+ # additive instead of a full replacement. The new serialized values
504
+ # will override any of these empty values.
505
+ if original && unsaved && key && self.class.additive_object_param?(key)
506
+ update = empty_values(original).merge(update)
507
+ end
408
508
 
409
509
  update
410
510
 
@@ -413,9 +513,30 @@ module Stripe
413
513
  end
414
514
  end
415
515
 
416
- private
516
+ # Produces a deep copy of the given object including support for arrays,
517
+ # hashes, and StripeObjects.
518
+ private_class_method def self.deep_copy(obj)
519
+ case obj
520
+ when Array
521
+ obj.map { |e| deep_copy(e) }
522
+ when Hash
523
+ obj.each_with_object({}) do |(k, v), copy|
524
+ copy[k] = deep_copy(v)
525
+ copy
526
+ end
527
+ when StripeObject
528
+ obj.class.construct_from(
529
+ deep_copy(obj.instance_variable_get(:@values)),
530
+ obj.instance_variable_get(:@opts).select do |k, _v|
531
+ Util::OPTS_COPYABLE.include?(k)
532
+ end
533
+ )
534
+ else
535
+ obj
536
+ end
537
+ end
417
538
 
418
- def dirty_value!(value)
539
+ private def dirty_value!(value)
419
540
  case value
420
541
  when Array
421
542
  value.map { |v| dirty_value!(v) }
@@ -426,17 +547,18 @@ module Stripe
426
547
 
427
548
  # Returns a hash of empty values for all the values that are in the given
428
549
  # StripeObject.
429
- def empty_values(obj)
550
+ private def empty_values(obj)
430
551
  values = case obj
431
- when Hash then obj
432
- when StripeObject then obj.instance_variable_get(:@values)
433
- else
434
- raise ArgumentError, "#empty_values got unexpected object type: #{obj.class.name}"
435
- end
436
-
437
- values.inject({}) do |update, (k, _)|
438
- update[k] = ''
439
- update
552
+ when Hash then obj
553
+ when StripeObject then obj.instance_variable_get(:@values)
554
+ else
555
+ raise ArgumentError,
556
+ "#empty_values got unexpected object type: " \
557
+ "#{obj.class.name}"
558
+ end
559
+
560
+ values.each_with_object({}) do |(k, _), update|
561
+ update[k] = ""
440
562
  end
441
563
  end
442
564
  end