Created
January 14, 2025 12:18
-
-
Save gil27/e0bd85d41724c9d50d566fe4ff68ffe0 to your computer and use it in GitHub Desktop.
This file contains 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
class Employee | |
attr_reader :id | |
attr_reader :name | |
def initialize(id, name) | |
@id = id | |
@name = name | |
end | |
end | |
class User | |
attr_reader :id | |
attr_reader :name | |
def initialize(id, name) | |
@id = id | |
@name = name | |
end | |
end | |
module Operator | |
class Equals | |
def initialize(x) | |
@x = x | |
end | |
attr_reader :x | |
def ==(other) | |
return false unless self.class == other.class && self.x.class == other.x.class | |
case x | |
when Employee then EmployeeMatcher.new(x, other.x).compare! | |
when User then UserMatcher.new(x, other.x).compare! | |
else | |
@x.id == other.x.id | |
end | |
end | |
end | |
class EmployeeMatcher | |
def initialize(x, y) | |
@x = x | |
@y = y | |
end | |
def compare! | |
@x.id == @y.id | |
end | |
end | |
class UserMatcher | |
def initialize(x, y) | |
@x = x | |
@y = y | |
end | |
def compare! | |
@x.name == @y.name | |
end | |
end | |
end | |
# Me guiei por: https://shopify.engineering/implementing-equality-in-ruby | |
employee1 = Employee.new(1, 'Gil') | |
employee2 = Employee.new(2, 'Gomes') | |
user1 = User.new(1, 'Gil') | |
user2 = User.new(1, 'Gil') | |
a = Operator::Equals.new(employee1) | |
b = Operator::Equals.new(employee2) | |
c = Operator::Equals.new(1) | |
d = Operator::Equals.new(user1) | |
e = Operator::Equals.new(user2) | |
p a == a # => true | |
p a == b # => false | |
p a == "soup" # => false | |
p a == c # => false | |
p a == d # => false | |
p d == e # => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment