Wednesday, 14 May 2014

Link: Service Objects in Rails

Steve Lorek has written a nice overview of Service Objects: What They Are, and When to Use Them.

"There has been a lot of discussion within the Ruby community around the service objects pattern. The term "service objects" may be unfamiliar to even seasoned Rails developers, because Rails itself implements the Model-View-Controller design pattern. There is no concept of a 'service' in a new Rails application. So it's understandable that this concept may seem foreign, and indeed non-obvious. However, I believe that the service objects pattern is well worth considering for any non-trivial Rails application."

It's a quick read, and gives a very good introduction/overview to when and why to use service objects in Rails.

Further to the above. If you have a Railscasts-pro account, you can watch this video on Service Objects.

It starts with an example of modularising out the functionality of a FAT model, using concerns. He then describes why he doesn't prefer that approach (my first introduction to the brilliant phrase "grep-driven-development") and finishes up with an alternative using service objects instead.

It's Rails-3 oriented - so you know you don't have to do anything special to include the concerns directory anymore... but otherwise his examples are still quite relevant and a great intro to the practicalities of how to actually go about a simple service-object and/or modularisation refactor.

Finally, don't forget some of the classic articles on this subject from DHH's Put chubby models on a diet with concerns to Bryan Helmkamp's 7 Patterns to Refactor Fat ActiveRecord Models

1 comment:

Anonymous said...

That's an interesting post! Service objects in Rails can definitely help one in designing clean and maintainable code. Here's also something about it:

Service objects in Rails