开发者

Rails structure, should I use a service layer in this case?

I'm new to Ruby and Rails and I'm making my first app. Basically I'm parsing HTML and sending it as JSON to the client.

Right now I've two sources for the HTML data but I could have more in the future. Because of this I thought that it'd be a good idea to remove the code 开发者_Python百科responsible to parse the HTML from the controller and put it into a service layer. I came up with this structure:

  • app
    • controllers
      • main_controller.rb
    • model
      • project.rb
      • task.rb
    • services
      • source1_service.rb
      • source2_service.rb

The MainController call both services to get the projects and tasks; each service parse its own HTML.

Is this a good solution? Is there a more RoR way to do this?


put your services in your models directory, there is no rule that all models have to extend from ActiveRecord::Base, but your services are opaquely data models to the rest of your app (if I understand you right). Ideally, let the service code mimic active record so other people that are just using your model code dont have to know its a different than any other model in your rails app.


Unlike in the Java world, 'the service layer classes' concept is not really popular/used in the RoR world. Its a good idea to remove that code form your controllers (you want your controllers to be thin). But i think you can inject them to your models. If you feel its getting too complicated you can break up your extra code into modules and mixin those modules to your models.

Its not the one and only way of doing things though.

However if parsing HTML include some common logic that can be reused, even in another project its a good idea to put it inside the lib/ folder.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜