Created
January 26, 2015 16:12
-
-
Save carlthuringer/f288c25771a987fb3e3c to your computer and use it in GitHub Desktop.
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
class CalculatesTax | |
include LightService::Organizer | |
def self.for_order(order) | |
with(:order => order).reduce( | |
[FetchesTaxRangesAction, FetchesCachedTaxRangesAction], | |
LooksUpTaxPercentageAction, | |
CalculatesOrderTaxAction, | |
ProvidesFreeShippingAction | |
fallback: GenericErrorHandler | |
) | |
end | |
end | |
class GenericErrorHandler | |
include LightService::Action | |
expects :errors | |
promises :error_messaging | |
executed do |context| | |
error_messaging = errors.map do |error| | |
log(:error, error.message, error.backtrace) | |
error.message | |
end.join("; ") | |
end | |
end | |
class FetchesTaxRangesAction | |
include LightService::Action | |
expects :order | |
promises :tax_ranges | |
executed do |context| | |
tax_ranges = TaxRange.for_region(context.order.region) # Raises exceptions when things go wrong | |
end | |
end | |
class FetchesCachedTaxRangesAction | |
include LightService::Action | |
expects :order | |
promises :tax_ranges | |
executed do |context| | |
tax_ranges = CachedTaxRanges.for_region(context.order.region) # Raises exceptions when things go wrong | |
end | |
end | |
class LooksUpTaxPercentageAction | |
include LightService::Action | |
expects :order, :tax_ranges | |
promises :tax_percentage | |
executed do |context| | |
tax_percentage = tax_ranges.for_total(order.total) # Raises an exception when there are no ranges, or no applicable range for the total | |
end | |
end | |
class CalculatesOrderTaxAction | |
include ::LightService::Action | |
expects :order, :tax_percentage | |
executed do |context| | |
order.tax = (order.total * (tax_percentage/100)).round(2) | |
end | |
end | |
class ProvidesFreeShippingAction | |
include LightService::Action | |
expects :order | |
executed do |context| | |
if order.total_with_tax > 200 | |
# Let's say the bang indicates a method that may raise an exception, such as: | |
# FreeShippingNotAllowedInRegion | |
order.provide_free_shipping! | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment