Created
September 12, 2020 15:53
-
-
Save arefaslani/16d4e665cb2982462ff2450e4c8b279e to your computer and use it in GitHub Desktop.
Medium 702687394e3d-application-service
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
require 'dry/matcher/result_matcher' | |
module ApplicationService | |
module ClassMethods | |
def call(params, &block) | |
service_outcome = self.new.execute(params) | |
if block_given? | |
Dry::Matcher::ResultMatcher.call(service_outcome, &block) | |
else | |
service_outcome | |
end | |
end | |
end | |
module InstanceMethods | |
include Dry::Monads[:result, :do] | |
def execute(params) | |
yield validate_params(params) | |
super(params) | |
end | |
def validate_params(params) | |
if self.class.constants.include? :ValidationSchema | |
validation_outcome = self.class.const_get(:ValidationSchema).call(params) | |
return Failure(validation_outcome.errors.to_h) if validation_outcome.failure? | |
end | |
Success(params) | |
end | |
end | |
def self.included(klass) | |
klass.prepend InstanceMethods | |
klass.extend ClassMethods | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment