Skip to content

Commit

Permalink
Fix eql? checks for definition models in order to return true if they…
Browse files Browse the repository at this point in the history
… have the same content
  • Loading branch information
Goltergaul committed Oct 6, 2022
1 parent 583888b commit 0bc1c15
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/definition/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,12 @@ def new(**kwargs)
def ==(other)
return false unless other.is_a?(self.class)

@_attributes == other.instance_variable_get(:@_attributes)
@_attributes.hash == other.instance_variable_get(:@_attributes).hash
end
alias eql? ==

def hash
@_attributes.hash
end

def to_h
Expand Down
58 changes: 58 additions & 0 deletions spec/lib/definition/model_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,64 @@

expect(model_a == model_b).to be false
end

it "returns false if a model is compared with its hash representation" do
model_a = test_model_class.new(name: "John")

expect(model_a == model_a.to_h).to be false
end
end

describe ".eql?" do
it "returns true if both models have the same content" do
model_a = test_model_class.new(name: "John")
model_b = test_model_class.new(name: "John")

expect(model_a.eql?(model_b)).to be true
end

it "returns false if both models have different content" do
model_a = test_model_class.new(name: "John")
model_b = test_model_class.new(name: "Marie")

expect(model_a.eql?(model_b)).to be false
end

it "returns false if a model is compared with its hash representation" do
model_a = test_model_class.new(name: "John")

expect(model_a.eql?(model_a.to_h)).to be false
end
end

describe ".hash" do
it "returns the same value for two models with the same content" do
model_a = test_model_class.new(name: "John")
model_b = test_model_class.new(name: "John")

expect(model_a.hash).to eq(model_b.hash)
end

it "returns a different value for two models with different content" do
model_a = test_model_class.new(name: "John")
model_b = test_model_class.new(name: "Marie")

expect(model_a.hash).not_to eq(model_b.hash)
end

it "considers the same model as an identical hash key" do
model_a = test_model_class.new(name: "John")
model_b = test_model_class.new(name: "John")
model_c = test_model_class.new(name: "Marie")

test_hash = {}
test_hash[model_a] = "John"
test_hash[model_b] = "John"
test_hash[model_c] = "Marie"

expect(test_hash.keys.size).to be(2)
expect(test_hash.keys).to eql([model_b, model_c])
end
end

describe ".new" do
Expand Down

0 comments on commit 0bc1c15

Please sign in to comment.