Skip to content

Instantly share code, notes, and snippets.

@olivierlacan
Created June 27, 2012 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olivierlacan/3000501 to your computer and use it in GitHub Desktop.
Save olivierlacan/3000501 to your computer and use it in GitHub Desktop.
The Beauty of Decorators
// 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
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
// 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
@ericallam
Copy link

I'd also do something like:

 - if subscription.in_suspension?

to get rid of that ||

@olivierlacan
Copy link
Author

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