Skip to content

Commit 6d557e3

Browse files
authored
Merge pull request #31 from nhemsley/master
add eql? and hash methods to table object for using objects as hash keys
2 parents 71c1096 + 97cf751 commit 6d557e3

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

lib/airrecord/table.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,19 +215,25 @@ def serializable_fields(fields = self.fields)
215215
value = [ value ] unless value.is_a?(Enumerable)
216216
assocs = value.map { |assoc|
217217
assoc.respond_to?(:id) ? assoc.id : assoc
218-
}
218+
}
219219
[key, assocs]
220220
else
221221
[key, value]
222222
end
223223
}]
224224
end
225-
225+
226226
def ==(other)
227227
self.class == other.class &&
228228
serializable_fields == other.serializable_fields
229229
end
230230

231+
alias_method :eql?, :==
232+
233+
def hash
234+
serializable_fields.hash
235+
end
236+
231237
protected
232238

233239
def association(key)

test/table_test.rb

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ def test_comparison_different_classes
304304
end
305305

306306
def test_association_accepts_non_enumerable
307-
walrus = Walrus.new("Name" => "Wally")
307+
walrus = Walrus.new("Name" => "Wally")
308308
foot = Foot.new("Name" => "FrontRight", "walrus" => walrus)
309309

310310
foot.serializable_fields
@@ -315,4 +315,32 @@ def test_dont_update_if_equal
315315
walrus["Name"] = "Wally"
316316
assert walrus.updated_keys.empty?
317317
end
318+
319+
def test_equivalent_records_are_eql?
320+
walrus1 = Walrus.new("Name" => "Wally")
321+
walrus2 = Walrus.new("Name" => "Wally")
322+
323+
assert walrus1.eql? walrus2
324+
end
325+
326+
def test_non_equivalent_records_fail_eql?
327+
walrus1 = Walrus.new("Name" => "Wally")
328+
walrus2 = Walrus.new("Name" => "Wally2")
329+
330+
assert !walrus1.eql?(walrus2)
331+
end
332+
333+
def test_equivalent_hash_equality
334+
walrus1 = Walrus.new("Name" => "Wally")
335+
walrus2 = Walrus.new("Name" => "Wally")
336+
337+
assert_equal walrus1.hash, walrus2.hash
338+
end
339+
340+
def test_non_equivalent_hash_inequality
341+
walrus1 = Walrus.new("Name" => "Wally")
342+
walrus2 = Walrus.new("Name" => "Wally2")
343+
344+
assert walrus1.hash != walrus2.hash
345+
end
318346
end

0 commit comments

Comments
 (0)