Last active
September 1, 2015 22:21
-
-
Save ro31337/0ef33cbd85c445d1beeb to your computer and use it in GitHub Desktop.
EmailAddress value object bug
This file contains hidden or 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
| === 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