Refactor Stripe::Util.convert_to_stripe_object method

* Extract hash mapping into object_classes method/ivar
* Use Hash#fetch instead of `if` and `||=`
This commit is contained in:
Tim Craft 2013-07-05 18:41:34 +01:00
parent 616b169958
commit da6736478e

View File

@ -15,8 +15,8 @@ module Stripe
end end
end end
def self.convert_to_stripe_object(resp, api_key) def self.object_classes
types = { @object_classes ||= {
'charge' => Charge, 'charge' => Charge,
'customer' => Customer, 'customer' => Customer,
'invoiceitem' => InvoiceItem, 'invoiceitem' => InvoiceItem,
@ -28,16 +28,15 @@ module Stripe
'recipient' => Recipient, 'recipient' => Recipient,
'list' => ListObject 'list' => ListObject
} }
end
def self.convert_to_stripe_object(resp, api_key)
case resp case resp
when Array when Array
resp.map { |i| convert_to_stripe_object(i, api_key) } resp.map { |i| convert_to_stripe_object(i, api_key) }
when Hash when Hash
# Try converting to a known object class. If none available, fall back to generic APIResource # Try converting to a known object class. If none available, fall back to generic APIResource
if klass_name = resp[:object] object_classes.fetch(resp[:object]) { StripeObject }.construct_from(resp, api_key)
klass = types[klass_name]
end
klass ||= StripeObject
klass.construct_from(resp, api_key)
else else
resp resp
end end