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

So here is the deal. I have been working in the Ruby on Rails environment for 1 year now. Before that, I had been in C ++ / Java for almost ten years. I'm still trying to figure out what Ruby is when it comes to claims.

I am not worried about technical details. I know that TestUnit has statements that can be used in a test environment, and I know that I can add my own assert methods to my Ruby project and use them in Rails to block known conditions. The question is: what is Ruby for providing something in the code that I know should / should not happen?

For the record, I claimed in tests and raised in production. I still can not miss my statements about the production ...

Thanks! - = Ahmed = -

+4
source share
3 answers

In fact, statements should not be used in production code for two reasons.

  • assert x is very functional and, as such, is difficult to read. Using the raise / if command adds readability.

  • assert doesn't let you know what error will be caused if the condition fails. While,

    raise ObscureButInformitiveError if condition

    allows additional application layers to do something incredible. For example, admin email or logging.

+4
source

Let the error happen, then check the logs for what went wrong, and then fix it.
Rails automatically catches all uncaught exceptions, this will only ruin the only request that failed.

+1
source

There are no test statements in Ruby, but there are gems.

For example, Jim Weirich Given looks promising. Although the focus is on testing environments (rspec / minitest), but also:

... contains three statements intended for use in a non-test / nonspecific code. For example, here the square root function is decoded with pre and post-condition statements.

 require 'given/assertions' require 'given/fuzzy_number' include Given::Assertions include Given::Fuzzy def sqrt(n) Precondition { n >= 0 } result = Math.sqrt(n) Postcondition { result ** 2 == about(n) } result end 

To use without testing assertions, you need to require 'given/assertions' and then include the Given::Assertions module in what ever class uses the Precondition / Postcondition / Assert methods. The code block for these statements should always be a regular Ruby true / false value (the wait and wait methods from RSpec are not available).

Note that this example also uses fuzzy number matching, but this is not required for the statements themselves.

0
source

Source: https://habr.com/ru/post/1347164/


All Articles