Here are the requirements:
- If
initial_invoice?
isfalse
,existing_invoice
always exists. - If
initial_invoice?
istrue
andexisting_invoice
exists, I'd love to use theexisting_invoice
.
I'd love to refactor this code.
existing_invoice = find_existing_invoice(invoice_obj[:id])
invoice = if !initial_invoice?(invoice_obj) || existing_invoice.present?
existing_invoice
else
ac = Account.find_by(stripe_customer_id: invoice_obj[:customer])
create_initial_invoice(invoice_obj, ac)
end
private
def find_existing_invoice(id)
Invoice.find_by(stripe_invoice_id: id)
end
def initial_invoice?(invoice_obj)
sub_id = invoice_obj[:subscription]
return false if sub_id.nil?
sub = Stripe::Subscription.retrieve(sub_id)
return false unless invoice_obj[:period_start] == sub[:created]
true
end
update
invoice = if initial_invoice?(invoice_obj)
return existing_invoice if existing_invoice.present?
ac = Account.find_by(stripe_customer_id: invoice_obj[:customer])
create_initial_invoice(invoice_obj, ac)
else
existing_invoice
end
existing_invoice.present?
- isexisting_invoice
potentially nil? ... Caninitial_invoice?
be in the Invoice class so you can do this:existing_invoice.initial?
... Should the requirement "...existing_invoice
always exists" be explicitly checked up front; and then handle as an error if not? ... Iscreate_initial_invoice
different, really, from creating any invoice? Why the "special" method? If the invoice class had ainitial?
property then may not need special methods, onlyfind_invoice
andcreate_invoice
. Might DRY up some code and make client (caller) code simpler. \$\endgroup\$Invoice.find_by
finds initial invoices, andAccount.find_by
finds all other invoices? Yes? I'd write the top-level logic around this to make the difference clear, like, "IF initial_invoice then create-or-find initial-invoice ELSE create-or-find not-initial-invoice END." That emphasizes what I think is the real difference. Then checking/validating those requirements, if needed, are in proper context of the particular "create-or-find" method. In any case it really troubles me that I need a second object to tell me if I'm an initial_invoice. I should know that for myself. \$\endgroup\$