Last active
August 7, 2024 06:11
-
-
Save kyrylo/563a8cb6f44532b58ccb48bf0d30651f to your computer and use it in GitHub Desktop.
How to define service objects in Rails: the simple way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # frozen_string_literal: true | |
| class ApplicationService | |
| def self.call(...) | |
| new(...).call | |
| end | |
| def initialize(...) | |
| end | |
| end | |
| class CurrentIpService < ApplicationService | |
| def initialize(request) | |
| super | |
| @request = request | |
| end | |
| def call | |
| ip_headers = [ | |
| @request.env["HTTP_CF_CONNECTING_IP"], | |
| @request.env["HTTP_CLIENT_IP"], | |
| @request.env["HTTP_X_FORWARDED_FOR"], | |
| @request.env["HTTP_X_FORWARDED"], | |
| @request.env["HTTP_FORWARDED_FOR"], | |
| @request.env["HTTP_FORWARDED"], | |
| @request.env["REMOTE_ADDR"] | |
| ] | |
| (ip_headers.find(&:present?) || "127.0.0.1").split(",").first | |
| end | |
| end | |
| CurrentIpService.call(request) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use service objects in all of my Rails projects.
👷♂️ This is how I engineer them:
Define the ApplicationService class with the
callclass method that does nothing but accepts any params and initializes a service, then calls thecallinstance method immediatelyDefine the
initializeinstance method that does nothing but accepts any paramsDefine a service that inherits from ApplicationService and defines the
callmethod. If a service requires params, I define theinitializemethod, callsuper, then use the params. If you don't need params, then you don't need to defineinitializeat allImplement the
callmethod.That's all!
https://x.com/kyrylosilin/status/1820473128365019139