Ruby Design pattern: How does the BrainTree Cancel subscription works

Ruby Design pattern: How does the BrainTree Cancel subscription works

I just found great the way that the cancel subscription works(ruby pattern) in the braintree gem, that’s why I’m sharing this pattern with you guys:

Gem https://github.com/braintree/braintree_ruby

# Just execute this class method
Braintree::Subscription.cancel(subscription2.id)

Logic Behind the scenes

# lib/braintree/subscription.rb
module Braintree
  class Subscription
    def self.cancel(subscription_id)
      Configuration.gateway.subscription.cancel(subscription_id)
    end
  end
end

# lib/braintree/configuration.rb
module Braintree
  class Configuration
     def self.gateway # :nodoc:
       Braintree::Gateway.new(instantiate)
    end
    def self.instantiate # :nodoc:
      config = new(
        :custom_user_agent => @custom_user_agent,
        :endpoint => @endpoint,
        :environment => environment,
        :logger => logger,
        :merchant_id => merchant_id,
        :private_key => private_key,
        :public_key => public_key
      )
    end
  end
end

# lib/braintree/gateway.rb
module Braintree
  class Gateway
    def subscription
      SubscriptionGateway.new(self)
    end
  end
end

# lib/braintree/subscription_gateway.rb
module Braintree
  class SubscriptionGateway
    def cancel(subscription_id)
      response = @config.http.put "/subscriptions/#{subscription_id}/cancel"
      if response[:subscription]
        SuccessfulResult.new(:subscription => Subscription._new(@gateway, response[:subscription]))
      elsif response[:api_error_response]
        ErrorResult.new(@gateway, response[:api_error_response])
      else
        raise UnexpectedError, "expected :subscription or :api_error_response"
      end
    rescue NotFoundError
      raise NotFoundError, "subscription with id #{subscription_id.inspect} not found"
    end
  end
end

No Comments

Post A Comment