Skip to content

Instantly share code, notes, and snippets.

@arefaslani
Created September 12, 2020 15:53
Show Gist options
  • Save arefaslani/16d4e665cb2982462ff2450e4c8b279e to your computer and use it in GitHub Desktop.
Save arefaslani/16d4e665cb2982462ff2450e4c8b279e to your computer and use it in GitHub Desktop.
Medium 702687394e3d-application-service
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