-
-
Save t0nylombardi/c6671135e208e23cb71e46fd61c1ae37 to your computer and use it in GitHub Desktop.
Application Service that allows to call classes and handle errors.
This file contains 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 | |
class Failure < StandardError; end | |
class ServiceFailed < StandardError | |
def initialize(msg = nil) | |
super | |
end | |
end | |
include ActiveModel::Validations | |
attr_reader :result, :success | |
alias success? success | |
def self.call(...) | |
new(...).call | |
end | |
def self.call!(...) | |
response = new(...).call | |
return response if response.success? | |
raise ServiceFailed, response.errors.full_messages.to_sentence unless response.success? | |
end | |
def call | |
if errors.empty? && valid? | |
@result = execute! | |
@success = true | |
else | |
@success = false | |
end | |
self | |
rescue Failure | |
self | |
end | |
private | |
def execute! | |
raise NotImplementedError | |
end | |
def fail! | |
@success = false | |
raise Failure | |
end | |
def log_error(message) | |
Rails.logger.error(message) | |
end | |
def map_errors(result_error_object:, current_error:) | |
current_error.each_key do |error_key| | |
result_error_object.add(error_key, current_error[error_key].to_sentence) | |
end | |
result_error_object | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment