Skip to content

Instantly share code, notes, and snippets.

@ro31337
Last active September 1, 2015 22:21
Show Gist options
  • Select an option

  • Save ro31337/0ef33cbd85c445d1beeb to your computer and use it in GitHub Desktop.

Select an option

Save ro31337/0ef33cbd85c445d1beeb to your computer and use it in GitHub Desktop.
EmailAddress value object bug
=== Buggy ===
class EmailAddress
include Comparable
def initialize(string)
if string =~ /@/
@raw_email_address = string.downcase.strip
else
raise ArgumentError, "email address must have an '@'"
end
end
def <=>(other)
raw_email_address <=> other.to_s # <-- BUG IS HERE
end
def to_s
raw_email_address
end
protected
attr_reader :raw_email_address
end
=== Test ===
irb(main):024:0> EmailAddress.new("user@example.com") == EmailAddress.new("user@example.com")
=> true
irb(main):025:0> EmailAddress.new("user@example.com") == EmailAddress.new("User@example.com")
=> true
irb(main):026:0> EmailAddress.new("user@example.com") == "user@example.com"
=> true
irb(main):027:0> EmailAddress.new("user@example.com") == "User@example.com"
=> false
=== Fixed ===
class EmailAddress
include Comparable
def initialize(string)
if string =~ /@/
@raw_email_address = string.downcase.strip
else
raise ArgumentError, "email address must have an '@'"
end
end
def <=>(other)
raw_email_address <=> other.to_s.downcase.strip # <<-- FIXED HERE
end
def to_s
raw_email_address
end
protected
attr_reader :raw_email_address
end
=== Test ===
irb(main):024:0> EmailAddress.new("user@example.com") == EmailAddress.new("user@example.com")
=> true
irb(main):025:0> EmailAddress.new("user@example.com") == EmailAddress.new("User@example.com")
=> true
irb(main):026:0> EmailAddress.new("user@example.com") == "user@example.com"
=> true
irb(main):027:0> EmailAddress.new("user@example.com") == "User@example.com"
=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment