Skip to content

Instantly share code, notes, and snippets.

@ratnikov
Created September 23, 2008 16:42
Show Gist options
  • Save ratnikov/12327 to your computer and use it in GitHub Desktop.
Save ratnikov/12327 to your computer and use it in GitHub Desktop.
Error:
[dfr@beta trunk]$ ruby test/unit/has_attribute_based_equality_test.rb -n test_is_equal_by
Loaded suite test/unit/has_attribute_based_equality_test
Started
E
Finished in 0.005169 seconds.
1) Error:
test_is_equal_by(HasAttributeBasedEqualityTest):
LocalJumpError: unexpected return
/home/dfr/webitects/trunk/lib/has_attribute_based_equality.rb:7:in `eql?'
/home/dfr/webitects/trunk/lib/has_attribute_based_equality.rb:5:in `each'
/home/dfr/webitects/trunk/lib/has_attribute_based_equality.rb:5:in `eql?'
/home/dfr/webitects/trunk/lib/has_attribute_based_equality.rb:15:in `=='
test/unit/has_attribute_based_equality_test.rb:29:in `should_be_not_equal'
test/unit/has_attribute_based_equality_test.rb:16:in `test_is_equal_by'
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/testing/default.rb:7:in `run'
1 tests, 5 assertions, 0 failures, 1 errors
[dfr@beta trunk]$
module HasAttributeBasedEquality
def is_equal_by *attributes
include(Module.new do
define_method :eql? do |other|
attributes.each do |attr|
unless self.send(attr) == other.send(attr)
return false
end
end
true
end
define_method :hash do
attributes.map { |attr| send(attr) }.hash
end
def == other; eql?(other) end
end)
end
end
# includes the is_equal_by hook into all objects without enabling the functionality by default
Class.class_eval { include HasAttributeBasedEquality }
class HasAttributeBasedEqualityTest < ActiveSupport::TestCase
def test_truth
assert true
end
def test_is_equal_by
foo_class = Class.new
foo_class.class_eval do
attr_accessor :a, :b, :c
def initialize *args; @a, @b, @c = args end
is_equal_by :a, :b
end
should_be_equal foo_class.new("1", "2", "3"), foo_class.new("1", "2", "5")
should_be_not_equal foo_class.new("1", "2", "3"), foo_class.new("1", "3", "2")
end
private
def should_be_equal foo, bar
assert_equal foo, bar
assert foo.eql?(bar), "#{foo.inspect} should be eql? to #{bar.inspect}."
assert_equal foo.hash, bar.hash, "#{foo.inspect} should have same hash code as #{bar.inspect}."
assert (foo == bar), "#{foo.inspect} should be == #{bar.inspect}."
end
def should_be_not_equal foo, bar
assert_not_equal foo, bar
assert !foo.eql?(bar), "#{foo.inspect} should not be eql? to #{bar.inspect}."
assert_not_equal foo.hash, bar.hash, "#{foo.inspect} should not have same hash code as #{bar.inspect}."
assert (foo != bar), "#{foo.inspect} should be != #{bar.inspect}."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment