Sha256: b1240924a315469b538da88a59290514ecd8c5aace6d8fa913343636223af772

Contents?: true

Size: 986 Bytes

Versions: 5

Compression:

Stored size: 986 Bytes

Contents

module Spree
  class Subscription < Spree::Base
    module ApiHandler
      extend ActiveSupport::Concern

      included do
        attr_accessor :card_token
        before_create :subscribe
        before_update :unsubscribe, :if => [:unsubscribed_at_changed?, :unsubscribed_at?]
      end

      def subscribe
        provider.subscribe(self)
        self.subscribed_at = Time.current
      end

      def unsubscribe
        provider.unsubscribe(self)
      end

      def save_and_manage_api(*args)
        begin
          new_record? ? save : update_attributes(*args)
        rescue provider.error_class, ActiveRecord::RecordNotFound => e
          logger.error "Error while subscribing: #{e.message}"
          errors.add :base, "There was a problem with your credit card"
          false
        end
      end

      def provider
        plan.try(:recurring).present? ? plan.recurring : (raise ActiveRecord::RecordNotFound.new("Provider not found."))
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
spree_account_recurring-2.0.0 app/models/concerns/spree/subscription/api_handler.rb
spree_account_recurring-1.3.1 app/models/concerns/spree/subscription/api_handler.rb
spree_account_recurring-1.2.1 app/models/concerns/spree/subscription/api_handler.rb
spree_account_recurring-1.3.0 app/models/concerns/spree/subscription/api_handler.rb
spree_account_recurring-1.2.0 app/models/concerns/spree/subscription/api_handler.rb