- Design patterns are just tools that help us constructing a software.
** Template Method pattern In the Template Method pattern, we create a skeletal class and it is basis for various subclasses or concrete classes. Within in the skeletal class, there are abstract methods, which in turn, will be overridden by the methods of subclasses.
Let's take an example of simple payment system,
Usually, the payment process has the same flow regardless of the provider we use.
The flow of our example payment system is,
- Authenticate the merchant (our application) with the provider
- Send the User's card data with the amount of order
- Receive confirmation or error from the provider
class StripePayment
def initialize card, amount
@api_key = ENV['STRIPE_API_KEY']
@card = card
@amount = amount
end
def process_payment!
authenticate_merchant && make_payment
end
def authenticate_merchant
begin
return true if Stripe::Merchant.authenticate @api_key
rescue Stripe::MerchantError => e
Rails.logger.error "Cannot establish connection between Merchant and Provider."
return false
rescue Stripe::ProviderUnreachable => e
Rails.logger.error "Provider unreachable."
return false
end
end
def make_payment
begin
return true if Stripe::Payment.process! @api_key, @card, @amount
rescue Stripe::PaymentUnprocessable => e
Rails.logger.error "Payment unprocessable, try again."
return false
end
end
end