DEV Community

Emanuele 🍕
Emanuele 🍕

Posted on

1

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?

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more