Skip to content

Instantly share code, notes, and snippets.

@MaherSaif
Forked from kyrylo/service.rb
Created August 6, 2024 12:22
Show Gist options
  • Save MaherSaif/41b9df27855c14f8d40f4c446459d9c6 to your computer and use it in GitHub Desktop.
Save MaherSaif/41b9df27855c14f8d40f4c446459d9c6 to your computer and use it in GitHub Desktop.
How to define service objects in Rails: the simple way
# 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