Skip to content

Instantly share code, notes, and snippets.

@kattak
Last active November 24, 2020 11:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kattak/679a2c628569672b954003b6d22137f5 to your computer and use it in GitHub Desktop.
Save kattak/679a2c628569672b954003b6d22137f5 to your computer and use it in GitHub Desktop.
Service Objects in Rails

##What are Service Objects?


 Service objects contain business logic with an interface that is easy to test.
 View > Controller > Model, but sometimes need other data, i.e. from an API

Where are service objects located?

├── app
│   ├── assets
│   ├── channels
│   ├── controllers
│   ├── helpers
│   ├── jobs
│   ├── mailers
│   ├── models
│   ├── **services**
│   └── views

Some preliminary concepts

  • Business logic
  • Skinny models, fat controllers
  • Skinny models, fat controllers, use service objects for application logic
  • Ruby's call method
  • Dependency Injection (DI)
  • Single Responsibility Principle (SRY)
  • Plain Old Ruby Objects (PORO)

All dem buzzwords

🐝 🐝 🐝 🐝 🐝 🐝 🐝

  • Business logic = rules how data can be created, displayed, stored, and changed
  • Skinny models, fat controllers = don't want models to have all this extra stuff
  • Skinny models, skinny controllers, use service objects for application logic
  • Ruby's call method = See here for an example: https://repl.it/EzaH/0
  • Dependency Injection (DI) =
  • Single Responsibility Principle (SRY)
  • Plain Old Ruby Objects (PORO)

(help from Wikipedia)

##When should I use service objects?

  • Processing a payment via an external API like Stripe or Braintree
  • Validating a comment is not spam or contains prohibited information
  • User is sent a "forgot your password email"
  • Posting to Facebook
  • Compiling an archive of the user's data for them to download (reaching across multiple models)
  • Reaching across multiple models OR external API
  • Action is not a core concern of the underlying model (timing out on a form after a period of time has passed)

** What else? **

###Useful links & resources

Call and complicated stuff http://blog.sundaycoding.com/blog/2014/11/25/my-take-on-services-in-rails/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment