A very (VERY) simple gem for Rails that adds a generator for easily creating a service class and its accompanying spec or test unit file.
Rails 4 and higher
Add this line to your application's Gemfile:
And then execute:
Or install it yourself as:
$ gem install rails_services
$ rails generate rails_services:create Service Model|Controller Sub-folder [opt] --instance [yes (default), no] $ rails generate rails_services:destroy Service Model|Controller Sub-folder [opt] --instance [yes (default), no]
Sub-folders are optional but, at this time, you may only use one sub-folder. I generally use the sub-folders when I have a naturally grouped set of services.
The instance argument was added in version 2.0.0. It is also optional but does default to
yes if omitted. In previous iterations of this gem
as well as in my early use of service layers, I did not instantiate my service classes; rather, I created adn accessed them at the class level,
calling class methods (i.e., those defined with
I was never satisfied with this and, sometime in the last few months, I read a now-lost blog post on utilizing a
BaseService class and
instantiating your actual service. I prefer this new approach, for lack of a better word, and have decided to add it to this gem, as the
default style used going forward (starting with 2.0.0).
The primary change in version 2 is that old services, those that do not include the
BaseService class, called
and accessed methods that were all defined with
self.. You do not have to choose one style over another; in fact,
you can mix and match the styles, if you wish.
Converting Old Service Classes - Should you want to update your older/previously built services with this approach, you only need to do the following:
# include the base service in your class class ClassName include BaseService # Then ... change the method signatures, simply removing "self." from the definition def self.call # ... end # becomes def call # ... end # and so on for other, similarly defined methods
Two files are created (spec or test based on your
- Fork it ( https://github.com/imageaid/rails_services/fork )
- Create your feature branch (
git checkout -b my-new-feature)
- Commit your changes (
git commit -am 'Add some feature')
- Push to the branch (
git push origin my-new-feature)
- Create a new Pull Request