Advertisement
Guest User

Untitled

a guest
Sep 1st, 2015
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. === Buggy ===
  2.  
  3. class EmailAddress
  4. include Comparable
  5.  
  6. def initialize(string)
  7. if string =~ /@/
  8. @raw_email_address = string.downcase.strip
  9. else
  10. raise ArgumentError, "email address must have an '@'"
  11. end
  12. end
  13.  
  14. def <=>(other)
  15. raw_email_address <=> other.to_s # <-- BUG IS HERE
  16. end
  17.  
  18. def to_s
  19. raw_email_address
  20. end
  21.  
  22. protected
  23.  
  24. attr_reader :raw_email_address
  25. end
  26.  
  27.  
  28. === Test ===
  29.  
  30. irb(main):024:0> EmailAddress.new("user@example.com") == EmailAddress.new("user@example.com")
  31. => true
  32. irb(main):025:0> EmailAddress.new("user@example.com") == EmailAddress.new("User@example.com")
  33. => true
  34. irb(main):026:0> EmailAddress.new("user@example.com") == "user@example.com"
  35. => true
  36. irb(main):027:0> EmailAddress.new("user@example.com") == "User@example.com"
  37. => false
  38.  
  39. === Fixed ===
  40.  
  41. class EmailAddress
  42. include Comparable
  43.  
  44. def initialize(string)
  45. if string =~ /@/
  46. @raw_email_address = string.downcase.strip
  47. else
  48. raise ArgumentError, "email address must have an '@'"
  49. end
  50. end
  51.  
  52. def <=>(other)
  53. raw_email_address <=> other.to_s.downcase.strip # <<-- FIXED HERE
  54. end
  55.  
  56. def to_s
  57. raw_email_address
  58. end
  59.  
  60. protected
  61.  
  62. attr_reader :raw_email_address
  63. end
  64.  
  65. === Test ===
  66.  
  67. irb(main):024:0> EmailAddress.new("user@example.com") == EmailAddress.new("user@example.com")
  68. => true
  69. irb(main):025:0> EmailAddress.new("user@example.com") == EmailAddress.new("User@example.com")
  70. => true
  71. irb(main):026:0> EmailAddress.new("user@example.com") == "user@example.com"
  72. => true
  73. irb(main):027:0> EmailAddress.new("user@example.com") == "User@example.com"
  74. => true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement