From 307ec3db0fe26cbd1811d34a27e6637726ce23ce Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sat, 27 Dec 2014 19:46:36 -0700 Subject: [PATCH] Provide a better error message for unsupported classes in `serialize` We only support classes which provide a no-args constructor to use as a default value. We can provide a more helpful error message if we catch this when `serialize` is called, rather than letting it error when you try to assign the attribute. Fixes #18224 --- activerecord/CHANGELOG.md | 7 +++++++ activerecord/lib/active_record/coders/yaml_column.rb | 11 +++++++++++ activerecord/test/cases/serialized_attribute_test.rb | 6 ++++++ 3 files changed, 24 insertions(+) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 5dd5c53e9c..4a954c2cc6 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,10 @@ +* Provide a more helpful error message when an unsupported class is passed to + `serialize` + + Fixes #18224 + + *Sean Griffin* + * Add bigint primary key support for MySQL. Example: diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb index d3d7396c91..9ea22ed798 100644 --- a/activerecord/lib/active_record/coders/yaml_column.rb +++ b/activerecord/lib/active_record/coders/yaml_column.rb @@ -8,6 +8,7 @@ class YAMLColumn # :nodoc: def initialize(object_class = Object) @object_class = object_class + check_arity_of_constructor end def dump(obj) @@ -33,6 +34,16 @@ def load(yaml) obj end + + private + + def check_arity_of_constructor + begin + load(nil) + rescue ArgumentError + raise ArgumentError, "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor." + end + end end end end diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index c8441201ca..c261a5b1c0 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -264,4 +264,10 @@ def test_nil_is_not_changed_when_serialized_with_a_class assert_not topic.content_changed? end + + def test_classes_without_no_arg_constructors_are_not_supported + assert_raises(ArgumentError) do + Topic.serialize(:content, Regexp) + end + end end