Skip to content

Instantly share code, notes, and snippets.

@jameshwang
Last active August 29, 2015 14:00
Show Gist options
  • Save jameshwang/11152265 to your computer and use it in GitHub Desktop.
Save jameshwang/11152265 to your computer and use it in GitHub Desktop.
Refactoring subscription method in Account
# OLD WAY
def subscription
if parent.present?
parent.subscription
elsif current_subscription && current_subscription.active?
current_subscription
elsif cancelled?
subscriptions.detect { |sub| sub.cancelled? } || subscriptions.first
else
subscriptions.detect(&:active?) || subscriptions.first
end
end
# ===========================================================================
# POTENTIAL NEW WAY
def subscription
parent_subscription || active_current_subscription || cancelled_subscription || any_active_subscription
end
private
def parent_subscription
parent.subscription if parent.present?
end
def active_current_subscription
current_subscription if current_subscription.try(:active?)
end
def cancelled_subscription
subscriptions.detect(&:cancelled?) || subscriptions.first if cancelled?
end
def any_active_subscription
subscriptions.detect(&:active?) || subscriptions.first
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment