开发者

Where does business logic go in rails?

开发者 https://www.devze.com 2023-02-01 22:24 出处:网络
I\'m an ASP.NET MVC developer just starting with my first big project on rails however Im confused as where to put your business logic? on ASP.NET I create a library which contains services(Domain dri

I'm an ASP.NET MVC developer just starting with my first big project on rails however Im confused as where to put your business logic? on ASP.NET I create a library which contains services(Domain driven design) which handle business logic, I have heard that rails uses a concept of fat model skinny controller but I have some projects in ASP.NET which adding all the logic to the controller would create a big mess, is there any other way?开发者_开发技巧


Go with the concept of FatModels and SkinnyControllers. Your models should know how they behave and what they should do.

When your models get too fat, extract them out into re-usuable modules and include them in your module.

  • Example of taking a fat controller (with logic) and moving to a model
  • Example of taking code from the views and moving into the model

You can easily test behavior of models using RSpec (or test/unit or shoulda). Then you can test that the application behaves correctly using Cucumber.


"Business Logic" or some might call it "Domain Logic" doesn't belong anywhere near Rails and/or your .NET MVC project. Rails and MVC should depend on your Domain not the other way around. I would recommend reading up on the Onion Architecture from Jeffery Palermo or watch "Architecture the Lost Years" by Robert Martin. (I think that's that talk anyway). There are probably more resources than that, but you'll thank yourself later for treating both Rails and .NET MVC like the 3rd party frameworks they are, and not the main house of your application.


I think this blog article provides a good overview of a strategy of incorporating domain driven design with in the rails framework: http://www.smashingboxes.com/domain-logic-in-rails/

TL;DR

Refactor your classic rails models into repositories, and use a facade layer in the controllers to interact with your domain model.

I'm struggling with this a little my self, and as much as the Fat Controller pattern seems to prevail, anything "fat" in software seems to be a smell, violating single responsibility.


You can put business logic anywhere you want (even in views! though that's a bad idea).

I'd say if the logic is tied to a real-world object, then put it on the model. Otherwise, use the controller. But it's up to you to determine how to do it for your app. Models are for modeling things, and Controllers are for controlling things.

0

精彩评论

暂无评论...
验证码 换一张
取 消