Skip to content

Instantly share code, notes, and snippets.

@jeremyruppel
Forked from bmarini/model-view-ideas.rb
Created October 10, 2011 00:39
Show Gist options
  • Save jeremyruppel/1274419 to your computer and use it in GitHub Desktop.
Save jeremyruppel/1274419 to your computer and use it in GitHub Desktop.
Tradeoffs
class User < Struct.new(:name, :phone, :email)
end
# ---------------------------------------------------------------------------
# Extend on demand
# + no dependency on User class, could be reusable
# + composable
# - cannot unextend user object once extended, but this object could be short
# lived
# ---------------------------------------------------------------------------
module FormattedPhone
def phone
"(%s) %s-%s" % [ super[0,3], super[3,3], super[6,4] ]
end
end
module FormattedEmail
def email
"#{name} <#{super}>"
end
end
user = User.new "Ben Marini", "4155551212", "ben.marini@example.com"
user.extend FormattedPhone
user.extend FormattedEmail
p user.phone
p user.email
# ---------------------------------------------------------------------------
# Subclass
# - dependency to User class
# - end up with lots of subclasses
# ---------------------------------------------------------------------------
class FormattedUser < User
def phone
"(%s) %s-%s" % [ super[0,3], super[3,3], super[6,4] ]
end
def email
"#{name} <#{super}>"
end
end
user = FormattedUser.new "Ben Marini", "4155551212", "ben.marini@example.com"
p user.phone
p user.email
# ---------------------------------------------------------------------------
# Create a decorator
# - no dependency on User class
# + composable, although composition feels clumsier than the object extension
# composition
# ---------------------------------------------------------------------------
class PhoneFormatted
def initialize(source)
@source = source
end
def phone
"(%s) %s-%s" % [ @source.phone[0,3], @source.phone[3,3], @source.phone[6,4] ]
end
end
class EmailFormatted
end
user = User.new "Ben Marini", "4155551212", "ben.marini@example.com"
user_for_display = PhoneFormatted.new(user)
p user_for_display.phone
# ---------------------------------------------------------------------------
# Create a mix-in
# - creates more methods on User class
# - all user objects will inherit the methods, even if they don't need them
# ---------------------------------------------------------------------------
module PhoneFormatting
# Assumes super defines phone, a 10 char string of integers
def formatted_phone
"(%s) %s-%s" % [ phone[0,3], phone[3,3], phone[6,4] ]
end
end
class User
include PhoneFormatting
end
user = User.new "Ben Marini", "4155551212", "ben.marini@example.com"
p user.formatted_phone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment