Skip to content
Browse files

Merge pull request #16517 from sgrif/sg-comparable-attributes

Implement `==` on `Type::Value` and `Attribute`
  • Loading branch information...
2 parents b97204c + bc153cf commit 88d27ae9181151f448f39298adce9d1b7401a376 @rafaelfranca rafaelfranca committed Aug 16, 2014
View
7 activerecord/lib/active_record/attribute.rb
@@ -62,6 +62,13 @@ def initialized?
true
end
+ def ==(other)
+ self.class == other.class &&
+ name == other.name &&
+ value_before_type_cast == other.value_before_type_cast &&
+ type == other.type
+ end
+
protected
def initialize_dup(other)
View
7 activerecord/lib/active_record/type/value.rb
@@ -76,6 +76,13 @@ def changed_in_place?(*)
false
end
+ def ==(other)
+ self.class == other.class &&
+ precision == other.precision &&
+ scale == other.scale &&
+ limit == other.limit
+ end
+
private
def type_cast(value)
View
30 activerecord/test/cases/attribute_test.rb
@@ -138,5 +138,35 @@ def type_cast_from_database(value)
test "uninitialized attributes have no value" do
assert_nil Attribute.uninitialized(:foo, nil).value
end
+
+ test "attributes equal other attributes with the same constructor arguments" do
+ first = Attribute.from_database(:foo, 1, Type::Integer.new)
+ second = Attribute.from_database(:foo, 1, Type::Integer.new)
+ assert_equal first, second
+ end
+
+ test "attributes do not equal attributes with different names" do
+ first = Attribute.from_database(:foo, 1, Type::Integer.new)
+ second = Attribute.from_database(:bar, 1, Type::Integer.new)
+ assert_not_equal first, second
+ end
+
+ test "attributes do not equal attributes with different types" do
+ first = Attribute.from_database(:foo, 1, Type::Integer.new)
+ second = Attribute.from_database(:foo, 1, Type::Float.new)
+ assert_not_equal first, second
+ end
+
+ test "attributes do not equal attributes with different values" do
+ first = Attribute.from_database(:foo, 1, Type::Integer.new)
+ second = Attribute.from_database(:foo, 2, Type::Integer.new)
+ assert_not_equal first, second
+ end
+
+ test "attributes do not equal attributes of other classes" do
+ first = Attribute.from_database(:foo, 1, Type::Integer.new)
+ second = Attribute.from_user(:foo, 1, Type::Integer.new)
+ assert_not_equal first, second
+ end
end
end
View
6 activerecord/test/cases/types_test.rb
@@ -149,6 +149,12 @@ def test_string_to_time_with_timezone
end
end
+ def test_type_equality
+ assert_equal Type::Value.new, Type::Value.new
+ assert_not_equal Type::Value.new, Type::Integer.new
+ assert_not_equal Type::Value.new(precision: 1), Type::Value.new(precision: 2)
+ end
+
if current_adapter?(:SQLite3Adapter)
def test_binary_encoding
type = SQLite3Binary.new

0 comments on commit 88d27ae

Please sign in to comment.
Something went wrong with that request. Please try again.