Skip to content

Instantly share code, notes, and snippets.

@r-glebov
Forked from kyrylo/service.rb
Created August 6, 2024 15:37
Show Gist options
  • Select an option

  • Save r-glebov/7b7d8935f62a4a9129ca8e167033cfeb to your computer and use it in GitHub Desktop.

Select an option

Save r-glebov/7b7d8935f62a4a9129ca8e167033cfeb 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