Ruby on Rails Best practices - Big Controller vs Small Controller

眉间皱痕 提交于 2019-11-27 05:13:12

This is more of a long-form comment, since it explains the origin of your dilemma, but provides no solutions.

The problem actually is caused by misinterpretation of MVC, which RoR popularizes.

It is the combination of two factors, which are causing this implosion of controller:

  • On the one side you have anemic model, because, instead of real model layer, RoR uses collection of ORM instances. The reason for it is that Rails was originally created to be a framework for fast prototyping (generation of throw-away code). And prototyping is exactly what active record is best at. Using scaffolding, you can easily generate active record structures from existing databases.

    But this cause some of the domain business logic to leak in your controllers.

  • On the other side you have the non-existent view. Since the goal was prototyping, Rails favored getting rid of views, which can actually contain presentation logic, by merging them into the controllers. The, now missing, views were replace with simple templates, which are just called "views".

    This forces controllers to contain presentation logic.

These two factors would be the reason, why I am tempted to assert, that RoR is not even MVC framework. The resulting pattern is actually closer to Model-View-Presenter. Though it has been simplified to the point at which it starts to break Separation of Concerns.

Most of your logic does not belong in the controller. The controllers responsibility is to tie input (HTTP requests and their parameters) to output (your views). Everything else is business logic that should be implemented in the model - Sound in your case, it looks like. Each of your if blocks, for example, would be a good candidate to implement as an instance method of the Sound class. If you find yourself reusing code (like the AWS storage bit) across various models, implement them in a Module (under lib) and include that module in those models.

It looks like all of that should be refactored into a model (or library module) and broken into smaller functions. The best reason for this is because then you can set up unit tests to test the smaller parts individually. The controller simply needs to instantiate the model and return the data to the browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!