Skip to content

Instantly share code, notes, and snippets.

@joeljackson
Created April 30, 2015 17:33
Show Gist options
  • Save joeljackson/0b9967b09709fc2282e0 to your computer and use it in GitHub Desktop.
Save joeljackson/0b9967b09709fc2282e0 to your computer and use it in GitHub Desktop.
# This calss decides whether or not we should attempt to update a credit
# card via the account updater
class CreditCard::AccountUpdatePolicy
# Initializes the class
# @param [CreditCard] credit_card The credit card we want to check for updating
# @raise [StandardError] Raised if the credit card doesn't have it's transactions and orders loaded
def initialize(credit_card)
@credit_card = credit_card
end
# Determines if we should attempt to update this card
# @return [Boolean] Should we update the card or not
def should_update?
if (!Rails.env.production? && !Rails.env.staging?) && (!credit_card.transactions.loaded? || !credit_card.orders.loaded?) then
raise StandardError.new("Please preload the transactions and orders for this credit card")
end
Setting.automatic_account_updates? &&
created_before_threshold? &&
updated_before_threshold? &&
has_charged_order? &&
allowed_brands?
end
private
def created_before_threshold?
@credit_card.created_at < threshold_date
end
def updated_before_threshold?
@credit_card.transactions.detect { |t| t.human_readable_type == :account_updater && t.created_at > threshold_date }.nil?
end
def has_charged_order?
@credit_card.orders.detect { |o| o.charged_at.present? }
end
def allowed_brands?
@credit_card.brand == :visa || @credit_card.brand == :master
end
def threshold_date
Time.now - ( Setting.account_updater_threshold || 10).days
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment