Created
March 23, 2021 23:20
-
-
Save aristotelesbr/ee1e48788bd1d1bcafea80f9ce4c461a to your computer and use it in GitHub Desktop.
Usando a composição ao seu favor com dry-monads
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
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'pry' | |
gem 'dry-monads' | |
end | |
require 'dry/monads' | |
class ResolveFullName | |
include Dry::Monads[:result, :do] | |
def call(first_name:, last_name:, **) | |
first = String(first_name) | |
last = String(last_name) | |
return Failure('The name must be 3 characters') if first.size <= 2 | |
value = yield normalize_str(first, last) | |
result = yield resolve_name(value) | |
Success(result) | |
end | |
private | |
def normalize_str(first, last) | |
Success([first.strip!, last.strip!].map(&:downcase)) | |
end | |
def resolve_name(arr_names) | |
Success(arr_names.join(' ')) | |
end | |
end | |
module PromotionMailer | |
extend Dry::Monads[:result] | |
def self.call(name, email, content = 'Ofertas com 80% de desconto!') | |
# Generic class to send email | |
attrs = { | |
to: email, | |
name: name, | |
content: content | |
} | |
p '✉️ sending email...' | |
Success(attrs) | |
end | |
end | |
module WriteLog | |
extend Dry::Monads[:result] | |
def self.call(**args) | |
puts 'Writing in the logs...' | |
sleep(1) | |
puts args | |
puts '🎉 Done!' | |
Success('Done!') | |
end | |
end | |
result = ResolveFullName.new | |
result | |
.call(first_name: ' aristoteles', last_name: 'COUTINHO ') | |
.bind(PromotionMailer, '[email protected]') | |
.bind(WriteLog) | |
# Usando a composição ao seu favor com dry-monads | |
# 👉🏻 https://www.aristotelescoutinho.com.br/usando-a-composição-ao-seu-favor-com-dy-monads | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment