Assume users will delete their cookies at inopportune times

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-11-21

I have a global function in an e-commerce store to access the current_order

def current_order(options = {})
  return @current_order if @current_order

  # Pay attention to how it depends on a cookie being set
  @current_order = Order.where(id: cookies[:order_id]).first
end

Now, in parts of the checkout flow, this method is called for important payment-related activity

class PayPalController
  def finalize
    paypal_transaction = create_paypal_transaction!

    handle_double_finalize(paypal_transaction) && return
    # critical use of `current_order` function:
    current_order.mark_paid_with!(paypal_transaction)
    ..
  end
end

Every so often, a user would delete their cookies between placing the order and finalizing on PayPal. This meant the current_order method returned nil and everything blew up.

I rewrote this key controller action to therefore fetch an order by order_number params coming from the payment provider as a fall-back.

class PayPalController
  def finalize
    paypal_transaction = create_paypal_transaction!

    handle_double_finalize(paypal_transaction) && return
    order = current_order || Order.find_by_number(params[:order_number])
    order.mark_paid_with!(paypal_transaction)
    ..
  end
end

Lesson

Assume users will delete their cookies at the most inopportune times.