Advertisement
saasbook

Refactoring example: single level of abstraction

Mar 6th, 2012
668
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.46 KB | None | 0 0
  1. # Goal: when customer first logs in, see if they recently opted out of email.
  2. #  If yes, show a nice message encouraging them to opt back in.
  3. #  self.current_user returns the currently logged-in user as an ActiveRecord model.
  4.  
  5. # version 1
  6.  
  7. # in CustomersController
  8.  
  9. def show
  10.   if self.current_user.e_blacklist?  &&
  11.       self.current_user.valid_email_address?  &&
  12.       !(m = Option.value(:encourage_email_opt_in)).blank?
  13.     m << ' Click the Billing Address tab (above) to update your preferences.'
  14.     flash[:notice] ||= m
  15.   end
  16. end
  17.  
  18. # Problems:
  19. #  - mixes levels of abstraction
  20. #  - exposes implementation details of how we compute whether customer
  21. #       needs to see this message (ie of what "opted out of email" means)
  22. #  - how do we know what flash[:notice] was coming in?  if it was non-nil,
  23. #       this will never do anything - yet now requires us to know this
  24. #  - what we really want is once per login - this doesn't do that
  25.  
  26.  
  27. #  version 3
  28.  
  29. # in ApplicationController
  30.  
  31. def login_message
  32.   encourage_opt_in_message if self.current_user.has_opted_out_of_email?
  33. end
  34. #
  35. # ....
  36. #
  37. def encourage_opt_in_message
  38.   m = Option.value(:encourage_email_opt_in)
  39.   m << ' Click the Billing Address tab (above) to update your preferences.' unless m.blank?
  40.   return m
  41. end
  42.  
  43.  
  44. # in customer.rb
  45.  
  46. def has_opted_out_of_email?
  47.   e_blacklist? && valid_email_address?
  48. end
  49.  
  50. # in handler for Login action
  51.  
  52. flash[:notice] = login_message || "Logged in successfully"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement