提交 1c1aba77 编写于 作者: K Kir Shatrov

Indicate action that failed in YamlColumn

上级 d13bc5df
......@@ -14,7 +14,7 @@ def initialize(attr_name, object_class = Object)
def dump(obj)
return if obj.nil?
assert_valid_value(obj)
assert_valid_value(obj, action: "dump")
YAML.dump obj
end
......@@ -23,16 +23,16 @@ def load(yaml)
return yaml unless yaml.is_a?(String) && /^---/.match?(yaml)
obj = YAML.load(yaml)
assert_valid_value(obj)
assert_valid_value(obj, action: "load")
obj ||= object_class.new if object_class != Object
obj
end
def assert_valid_value(obj)
def assert_valid_value(obj, action:)
unless obj.nil? || obj.is_a?(object_class)
raise SerializationTypeMismatch,
"Attribute `#{@attr_name}` was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}"
"can't #{action} `#{@attr_name}`: was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}"
end
end
......
......@@ -43,7 +43,7 @@ def accessor
def assert_valid_value(value)
if coder.respond_to?(:assert_valid_value)
coder.assert_valid_value(value)
coder.assert_valid_value(value, action: "serialize")
end
end
......
......@@ -10,19 +10,19 @@ def test_initialize_takes_class
end
def test_type_mismatch_on_different_classes_on_dump
coder = YAMLColumn.new("attr_name", Array)
coder = YAMLColumn.new("tags", Array)
error = assert_raises(SerializationTypeMismatch) do
coder.dump("a")
end
assert_equal %{Attribute `attr_name` was supposed to be a Array, but was a String. -- "a"}, error.to_s
assert_equal %{can't dump `tags`: was supposed to be a Array, but was a String. -- "a"}, error.to_s
end
def test_type_mismatch_on_different_classes
coder = YAMLColumn.new("attr_name", Array)
coder = YAMLColumn.new("tags", Array)
error = assert_raises(SerializationTypeMismatch) do
coder.load "--- foo"
end
assert_equal %{Attribute `attr_name` was supposed to be a Array, but was a String. -- "foo"}, error.to_s
assert_equal %{can't load `tags`: was supposed to be a Array, but was a String. -- "foo"}, error.to_s
end
def test_nil_is_ok
......
......@@ -250,7 +250,7 @@ def test_unexpected_serialized_type
error = assert_raise(ActiveRecord::SerializationTypeMismatch) do
topic.content
end
expected = "Attribute `content` was supposed to be a Array, but was a Hash. -- {:zomg=>true}"
expected = "can't load `content`: was supposed to be a Array, but was a Hash. -- {:zomg=>true}"
assert_equal expected, error.to_s
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册