Pros and cons of using callbacks for domain logic in Rails

前端 未结 6 576
春和景丽
春和景丽 2021-01-30 04:50

What do you see as the pros and cons of using callbacks for domain logic? (I\'m talking in the context of Rails and/or Ruby projects.)

To start the discussion, I wanted

6条回答
  •  情话喂你
    2021-01-30 05:25

    In my opinion, the best scenario for using callbacks is when the method firing it up has nothing to do with what's executed in the callback itself. For example, a good before_save :do_something should not execute code related to saving. It's more like how an Observer should work.

    People tend to use callbacks only to DRY their code. It's not bad, but can lead to complicated and hard to maintain code, because reading the save method does not tell you all it does if you don't notice a callback is called. I think it is important to explicit code (especially in Ruby and Rails, where so much magic happens).

    Everything related to saving should be be in the save method. If, for example, the callback is to be sure that the user is authenticated, which has no relation to saving, then it is a good callback scenario.

提交回复
热议问题