{"id":15466210,"url":"https://github.com/manuelmeurer/services","last_synced_at":"2025-08-24T09:41:28.743Z","repository":{"id":17146405,"uuid":"19913065","full_name":"manuelmeurer/services","owner":"manuelmeurer","description":"A nifty service layer for your Rails app","archived":false,"fork":false,"pushed_at":"2025-08-11T17:23:38.000Z","size":767,"stargazers_count":222,"open_issues_count":2,"forks_count":7,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-08-18T22:50:36.868Z","etag":null,"topics":["rails","service-layer","services"],"latest_commit_sha":null,"homepage":"https://manuelmeurer.com/services","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/manuelmeurer.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-05-18T14:59:37.000Z","updated_at":"2023-09-08T16:47:42.000Z","dependencies_parsed_at":"2024-10-31T09:03:13.385Z","dependency_job_id":null,"html_url":"https://github.com/manuelmeurer/services","commit_stats":{"total_commits":304,"total_committers":3,"mean_commits":"101.33333333333333","dds":0.009868421052631526,"last_synced_commit":"2215adde9f1b9476785843ab0ed6e877488f69c5"},"previous_names":["krautcomputing/services"],"tags_count":81,"template":false,"template_full_name":null,"purl":"pkg:github/manuelmeurer/services","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manuelmeurer%2Fservices","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manuelmeurer%2Fservices/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manuelmeurer%2Fservices/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manuelmeurer%2Fservices/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/manuelmeurer","download_url":"https://codeload.github.com/manuelmeurer/services/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manuelmeurer%2Fservices/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":271837674,"owners_count":24831457,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-24T02:00:11.135Z","response_time":111,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["rails","service-layer","services"],"created_at":"2024-10-02T01:05:27.446Z","updated_at":"2025-08-24T09:41:28.711Z","avatar_url":"https://github.com/manuelmeurer.png","language":"Ruby","funding_links":["https://www.buymeacoffee.com/279lcDtbF)!"],"categories":[],"sub_categories":[],"readme":"# Services\n\n[![Gem Version](https://badge.fury.io/rb/services.png)](http://badge.fury.io/rb/services)\n[![CI](https://github.com/manuelmeurer/services/actions/workflows/ci.yml/badge.svg)](https://github.com/manuelmeurer/services/actions/workflows/ci.yml)\n\nServices is a collection of modules and base classes that let you simply add a service layer to your Rails app.\n\n## Motivation\n\nA lot has been written about service layers (service objects, SOA, etc.) for Rails. There are of course advantages and disadvantages, but after using Services since 2013 in several Rails apps, I must say that in my opinion the advantages far outweigh the disadvantages.\n\n**The biggest benefit you get when using a service layer, in my opinion, is that it gets so much easier to reason about your application, find a bug, or implement new features, when all your business logic is in services, not scattered in models, controllers, helpers etc.**\n\n## Usage\n\nFor disambiguation: in this README, when you read \"Services\" with a uppercase \"S\", this gem is meant, whereas with \"services\", well, the plural of service is meant.\n\n### Requirements\n\n#### Ruby \u003e= 2.7\n\n#### Rails \u003e= 6.0\n\n#### Redis \u003e= 3.0\n\nRedis is used at several points, e.g. to store information about the currently running services, so you can enforce uniqueness for specific services, i.e. make sure no more than one instance of such a service is executed simultaneously.\n\n#### Postgres (optional)\n\nThe SQL that `Services::Query` (discussed further down) generates is optimized for Postgres. It might work with other databases but it's not guaranteed. If you're not using Postgres, you can still use all other parts of Services, just don't use `Services::Query` or, even better, submit a [pull request](https://github.com/manuelmeurer/services/issues) that fixes it to work with your database!\n\n#### Sidekiq (optional)\n\nTo process services in the background, Services uses [Sidekiq](https://github.com/mperham/sidekiq). If you don't need background processing, you can still use Services without Sidekiq. When you then try to enqueue a service for background processing, an exception will be raised. If you use Sidekiq, make sure to load the Services gem after the Sidekiq gem.\n\n### Basic principles\n\nServices is based on a couple of basic principles around what a service should be and do in your app:\n\nA service...\n\n* does only one thing and does it well (Unix philosophy)\n* can be run synchronously (i.e. blocking/in the foreground) or asynchronously (i.e. non-blocking/in the background)\n* can be configured as \"unique\", meaning only one instance of it should be run at any time (including or ignoring parameters)\n* logs all the things (start time, end time, duration, caller, exceptions etc.)\n* has its own exception class(es) which all exceptions that might be raised inherit from\n* does not care whether certain parameters are objects or object IDs\n\nApart from these basic principles, you are free to implement the actual logic in a service any way you want.\n\n### Conventions\n\nFollow these conventions when using Services in your Rails app, and you'll be fine:\n\n* Let your services inherit from `Services::Base`\n* Let your query objects inherit from `Services::Query`\n* Put your services in `app/services/`\n* Decide if you want to use a `Services` namespace or not. Namespacing your service allows you to use a name for them that some other class or module in your app has (e.g. you can have a `Services::Maintenance` service, yet also a `Maintenance` module in `lib`). Not using a namespace saves you from writing `Services::` everytime you want to reference a service in your app. Both approaches are fine, pick one and stick to it.\n* Give your services \"verby\" names, e.g. `app/services/users/delete.rb` defines `Users::Delete` (or `Services::Users::Delete`, see above). If a service operates on multiple models or no models at all, don't namespace them (`Services::DoStuff`) or namespace them by logical groups unrelated to models (`Services::Maintenance::CleanOldStuff`, `Services::Maintenance::SendDailySummary`, etc.)\n* Some services call other services. Try to not combine multiple calls to other services and business logic in one service. Instead, some services should contain only business logic and other services only a bunch of service calls but no (or little) business logic. This keeps your services nice and modular.\n\n### Configuration\n\nYou can/should configure Services in an initializer:\n\n```ruby\n# config/initializers/services.rb\nServices.configure do |config|\n  config.logger = Services::Logger::Redis.new(Redis.new)    # see [Logging](#Logging)\n  config.redis  = Redis.new                                 # optional, if `Redis.current` is defined. Otherwise it is recommended to use\n                                                            # a [connection pool](https://github.com/mperham/connection_pool) here instead of simply `Redis.new`.\nend\n```\n\n### Rails autoload fix for `Services` namespace\n\nBy default, Rails expects `app/services/users/delete.rb` to define `Users::Delete`. If you want to use the `Services` namespace for your services, we want it to expect `Services::Users::Delete`. To make this work, add the `app` folder to the autoload path:\n\n```ruby\n# config/application.rb\nconfig.autoload_paths += [config.root.join('app')]\n```\n\nThis looks as if it might break things, but AFAIK it has never cause problems so far.\n\n### Services::Base\n\n`Services::Base` is the base class you should use for all your services. It gives you a couply of helper methods and defines a custom exception class for you.\n\nRead [the source](lib/services/base.rb) to understand what it does in more detail.\n\nThe following example service takes one or more users or user IDs as an argument and deletes the users:\n\n```ruby\nmodule Services\n  module Users\n    class Delete \u003c Services::Base\n      def call(ids_or_objects)\n        users = find_objects(ids_or_objects)\n        users.each do |user|\n          if user.posts.any?\n            raise Error, \"User #{user.id} has one or more posts, refusing to delete.\"\n          end\n          user.destroy\n          Mailer.user_deleted(user).deliver\n        end\n        users\n      end\n    end\n  end\nend\n```\n\nThis service can be called in several ways:\n\n```ruby\n# Execute synchronously/in the foreground\n\nServices::Users::Delete.call User.find(1)                # with a user object\nServices::Users::Delete.call User.where(id: [1, 2, 3])   # with a ActiveRecord::Relation returning user objects\nServices::Users::Delete.call [user1, user2, user3]       # with an array of user objects\nServices::Users::Delete.call 1                           # with a user ID\nServices::Users::Delete.call [1, 2, 3]                   # with an array of user IDs\n\n# Execute asynchronously/in the background\n\nServices::Users::Delete.call_async 1                     # with a user ID\nServices::Users::Delete.call_async [1, 2, 3]             # with multiple user IDs\n```\n\nAs you can see, you cannot use objects or a ActiveRecord::Relation as parameters when calling a service asynchronously since the arguments are serialized to Redis. This might change once Services works with [ActiveJob](https://github.com/rails/rails/tree/master/activejob) and [GlobalID](https://github.com/rails/globalid/).\n\nThe helper `find_objects` is used to allow the `ids_or_objects` parameter to be a object, object ID, array or ActiveRecord::Relation, and make sure you we dealing with an array of objects from that point on.\n\nIt's good practice to always return the objects a service has been operating on at the end of the service.\n\n### Services::Query\n\n`Services::Query` on the other hand should be the base class for all query objects.\n\nHere is an example that is used to find users:\n\n```ruby\nmodule Services\n  module Users\n    class Find \u003c Services::Query\n      convert_condition_objects_to_ids :post\n\n      private def process(scope, condition, value)\n        case condition\n        when :email, :name\n          scope.where(condition =\u003e value)\n        when :post_id\n          scope.joins(:posts).where(\"#{Post.table_name}.id\" =\u003e value)\n        end\n      end\n    end\n  end\nend\n```\n\nA query object that inherits from `Services::Query` always receives two parameters: an array of IDs and a hash of conditions. It always returns an array, even if none or only one object is found.\n\nWhen you write your query objects, the only method you have to write is `process` (preferably make it private). This method does the actual querying for all non-standard parameters (more about standard vs. non-standard parameters below).\n\nThis is how `Services::Users::Find` can be called:\n\n```ruby\nServices::Users::Find.call []                             # find all users, neither filtered by IDs nor by conditions\nServices::Users::Find.call [1, 2, 3]                      # find users with ID 1, 2 or 3\nServices::Users::Find.call 1                              # find users with ID 1 (careful: returns an array containing this one user, if found, otherwise an empty array)\nServices::Users::Find.call [], email: 'foo@bar.com'       # find users with this email address\nServices::Users::Find.call [1, 2], post: Post.find(1)     # find users with ID 1 or 2 and having the post with ID 1\nServices::Users::Find.call [1, 2], post: [Post.find(1)]   # same as above\nServices::Users::Find.call [1, 2], post: 1                # same as above\n```\n\nCheck out [the source of `Services::Query`](lib/services/query.rb) to understand what it does in more detail.\n\n#### Standard vs. non-standard parameters\n\nto be described...\n\n#### convert_condition_objects_to_ids\n\nAs with service objects, you want to be able to pass objects or IDs as conditions to query objects as well, and be sure that they behave the same way. This is what `convert_condition_objects_to_ids :post` does in the previous example: it tells the service object to convert the `post` condition, if present, to `post_id`.\n\nFor example, at some point in your app you have an array of posts and need to find the users that created these posts. `Services::Users::Find.call([], post: posts)` will find them for you. If you have a post ID on the other hand, simply use `Services::Users::Find.call([], post: post_id)`, or if you have a single post, use `Services::Users::Find.call([], post: post)`. Each of these calls will return an array of users, as you would expect.\n\n`Services::Query` takes an array of IDs and a hash of conditions as parameters. It then extracts some special conditions (:order, :limit, :page, :per_page) that are handled separately and passes a `ActiveRecord::Relation` and the remaining conditions to the `process` method that the inheriting class must define. This method should handle all the conditions, extend the scope and return it.\n\n### Helpers\n\nYour services inherit from `Services::Base` which makes several helper methods available to them:\n\n* `Rails.application.routes.url_helpers` is included so you use all Rails URL helpers.\n* `find_objects` and `find_object` let you automatically find object or a single object from an array of objects or object IDs, or a single object or object ID. The only difference is that `find_object` returns a single object whereas `find_objects` always returns an array.\n* `object_class` tries to figure out the class the service operates on. If you follow the service naming conventions and you have a service `Services::Products::Find`, `object_class` will return `Product`. Don't call it if you have a service like `Services::DoStuff` or it will raise an exception.\n\nYour services also automatically get a custom `Error` class, so you can `raise Error, 'Uh-oh, something has gone wrong!'` in `Services::MyService` and a `Services::MyService::Error` will be raised.\n\n### Logging\n\nYou can choose between logging to Redis or to a file, or turn logging off. By default logging is turned off.\n\n#### Redis\n\nto be described...\n\n#### File\n\nto be described...\n\n### Exception wrapping\n\nto be described...\n\n### Uniqueness checking\n\nto be described...\n\n### Background/asynchronous processing\n\nEach service can run synchronously (i.e. blocking/in the foreground) or asynchronously (i.e. non-blocking/in the background). If you want to run a service in the background, make sure it takes only arguments that can be serialized without problems (i.e. integers, strings, etc.). The background processing is done by Sidekiq, so you must set up Sidekiq in the Services initializer.\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n    gem 'services'\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install services\n\n## Contributing\n\n1. Fork it\n2. Create your feature branch (`git checkout -b my-new-feature`)\n3. Commit your changes (`git commit -am 'Add some feature'`)\n4. Push to the branch (`git push origin my-new-feature`)\n5. Create new Pull Request\n\n## Testing\n\nYou need Redis to run tests, check out the [Guardfile](Guardfile) which loads it automatically when you start Guard!\n\n## Support\n\nIf you like this project, consider [buying me a coffee](https://www.buymeacoffee.com/279lcDtbF)! :)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanuelmeurer%2Fservices","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmanuelmeurer%2Fservices","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanuelmeurer%2Fservices/lists"}