Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using asserts in Ruby production... yes or no?

So, here's the deal. I'm currently working in a Ruby on Rails environment and have been for ~1 year now. Before that I was in C++/Java land for almost a decade. I'm (still) trying to figure out what the Ruby way is when it comes to asserts.

I'm not worried about the technical detail. I know TestUnit has asserts which can be used in the testing environment and I know I can add my own assert methods to my Ruby project and use them in production Rails to lock down known conditions. The question is: What is the Ruby way for ensuring something in code that I know should/not happen?

For the record, I've been asserting in tests and raising in production. I still can't help but miss my production asserts...

Thanks! -=Ahmed=-

like image 959
Ahmish Avatar asked Apr 07 '11 19:04

Ahmish


2 Answers

Asserts really shouldn't be used in production code for two reasons.

  1. assert x is very functional, and as such hard to read. Using a raise/if combo adds readability.

  2. assert doesn't make it clear what error will be raised if the condition fails. While,

    raise ObscureButInformitiveError if condition

    lets the application layers further up do something relveant. Such as emailing an admin, or writing to a perticular log.

like image 181
diedthreetimes Avatar answered Sep 30 '22 13:09

diedthreetimes


Let the error happen, then check the logs for what went wrong, then fix it.
Rails catches all uncaught exceptions automatically, it will only mess up the single request the error happened in.

like image 22
x10 Avatar answered Sep 30 '22 13:09

x10