-
-
Save MaherSaif/41b9df27855c14f8d40f4c446459d9c6 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment