Created
June 27, 2012 00:45
-
-
Save olivierlacan/3000501 to your computer and use it in GitHub Desktop.
The Beauty of Decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ew, conditional soup | |
- subscription = current_user.subscription | |
%p Next bill date: | |
- if subscription.next_bill_on | |
%h4= subscription.next_bill_on.to_formatted_s(:long) | |
- else | |
%h4 Unknown | |
- if subscription.suspending? || subscription.suspended? | |
%p Suspended from: | |
%h4= subscription.next_bill_on.to_formatted_s(:long) | |
%p Until: | |
- if subscription.suspended_until | |
%h4= subscription.suspended_until.to_formatted_s(:long) | |
- else | |
%h4 Unknown |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SubscriptionDecorator < ApplicationDecorator | |
decorates :subscription | |
def next_bill_on | |
if model.try(:next_bill_on) | |
model.next_bill_on.to_formatted_s(:long) | |
else | |
'Unknown' | |
end | |
end | |
def suspended_until | |
if model.try(:suspended_until) | |
model.suspended_until.to_formatted_s(:long) | |
else | |
'Unknown' | |
end | |
end | |
end | |
# you could push the refactoring even further to remove the duplication above | |
def next_bill_on | |
format_date(:next_bill_on) | |
end | |
def suspended_until | |
format_date(:suspended_until) | |
end | |
private | |
def format_date(method) | |
method = method.to_sym | |
if model.send(method) | |
model.send(method).to_formatted_s(:long) | |
else | |
'Unknown' | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sweetly abstracted conditional logic through decorator | |
- subscription = SubscriptionDecorator.new(current_user.subscription) | |
%p Next bill date: | |
%h4= subscription.next_bill_on | |
- if subscription.suspending? || subscription.suspended? | |
%p Suspended from: | |
%h4= subscription.next_bill_on | |
%p Until: | |
%h4= subscription.suspended_until |
I actually have to account for both cases, so I exploded that into two conditions. But good point. :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd also do something like:
- if subscription.in_suspension?
to get rid of that
||