Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails service objects vs lib classes

Short version: when should I put something into app/services instead of into lib/.

I've been going down the service objects route recently, but I realised that sometimes I can't really decide weather I should extract something into a service object (which I have in app/services) or into a class in my lib folder.

One thing I usually look for is if the class needs access to params or other controller-specific things (i.e. as a param in the initializer), then I tend to put it into services.

What is the convention here? Proof (links) would be nice :)

like image 361
mrbrdo Avatar asked Apr 23 '13 00:04

mrbrdo


2 Answers

This is how I tend to think about code that goes in lib/:

  • It is not coupled to my app's domain models.
  • It can be reused on other projects.
  • It can potentially become its own gem. Thus, putting it in lib/ is the first step in that direction.

Services:

  • They tend to know a decent amount about the inner workings of domain models.
  • Perform work that is specific to business domain in my app.
  • Tend to be coupled to specific models.
like image 128
gylaz Avatar answered Sep 29 '22 13:09

gylaz


IMO, services are an abstraction of your domain. Lib stuff is for convenience classes, other stuff that doesnt directly relate to your models.

like image 25
cpuguy83 Avatar answered Sep 29 '22 11:09

cpuguy83