Created
April 23, 2025 20:31
-
-
Save andersondias/1945c0beebce2b58812013f5035c8b7b to your computer and use it in GitHub Desktop.
Sample code using the Operation + Result pattern
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
class CalculateShippingCost < Operation | |
def initialize(order) | |
@order = order | |
end | |
def perform | |
validation_result = validate_address | |
return validation_result if validation_result.failure? | |
calculate_shipping_cost | |
end | |
private | |
def calculate_shipping_cost | |
correios_result = calculate_with_correios | |
return correios_result if correios_result.success? | |
calculate_internally | |
end | |
def validate_address | |
if @order.address.blank? | |
Result.error("Address is required") | |
end | |
Result.ok | |
end | |
def calculate_with_correios | |
Shipping::Correios.perform(@order) | |
end | |
def calculate_internally | |
Shipping::Simulation.perform(@order) | |
end | |
end |
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
# Classe abstrata para operações | |
class Operation | |
class << self | |
def perform(*params) | |
new(*params).perform | |
end | |
end | |
#: -> Result | |
def perform | |
raise NotImplementedError | |
end | |
end |
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
class Result | |
attr_reader :data, :errors | |
def initialize(data, errors) | |
@data = data | |
@errors = errors | |
end | |
def success? | |
@errors.empty? | |
end | |
def failure? | |
!success? | |
end | |
class << self | |
def ok(data = nil) | |
new(data, []) | |
end | |
def error(errors) | |
new(nil, Array(errors)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment