DEV Community

Emanuele πŸ•
Emanuele πŸ•

Posted on

Instantiation or !Instantiation of Ruby classes?

The other day I was thinking,

should I always aim for the least memory use when I write Rails code or is any effort unimportant, given that behind the few lines of my own code there is always a plethora of framework calls?

We're now discussing the ethics of our RejectPendingOrderJob.

Simply put, an order is created in pending state and automatically rejected in 72 hours unless it has been approved in the meanwhile.

The job is enqueued with every pending order created, will execute in 72 hours and should do nothing unless the order is still pending.

# I believe a single SQL statement can execute this elegantly
def perform(order_id)
  Order.where(id: order_id, state: :pending).update_all(state: :rejected)
end

# The counter proposal involves the instantiation of the class, which I believe is redundant. 
def perform(order_id)
  order = Order.find(order_id)
  order.rejected! unless order.accepted?
end
What is your preference?

Top comments (1)

Collapse
 
ricsdeol profile image
Ricardo S. O. Leite

I'm prefer first way but I update updated_at something like this: Order.where(id: order_id, state: :pending).update_all(state: :rejected, updated_at: Time.zone.now)