##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
├── app
│ ├── assets
│ ├── channels
│ ├── controllers
│ ├── helpers
│ ├── jobs
│ ├── mailers
│ ├── models
│ ├── **services**
│ └── views
- 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)
🐝 🐝 🐝 🐝 🐝 🐝 🐝
- 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 method in Ruby https://ruby-doc.org/core-2.1.4/Method.html#method-i-call
-
Rails Guides: https://www.google.com/search?q=site:guides.rubyonrails.org+services nothing useful
-
Example: CreateComment checks comment for prohibited works https://github.com/adamniedzielski/service-objects-example shows how to test as well: https://github.com/adamniedzielski/service-objects-example/commit/a35d48b6a14f645a8a8764c7ad33ff880f757546
-
Example: CreditCardService parses form from user and sends API call to Stripe shows how to test service objects as well! https://blog.engineyard.com/2014/keeping-your-rails-controllers-dry-with-services
-
Strategy: 7 ways to decompose fat active record models (including service objects) http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
Call and complicated stuff http://blog.sundaycoding.com/blog/2014/11/25/my-take-on-services-in-rails/