Don't fail if object is nil, render null

This commit is contained in:
Michi Huber 2013-02-26 11:17:28 +01:00
parent 58a063eff0
commit c7a420d295
2 changed files with 23 additions and 0 deletions

View File

@ -267,6 +267,7 @@ module ActiveModel
# Returns a hash representation of the serializable
# object without the root.
def serializable_hash
return nil if @object.nil?
instrument(:serialize, :serializer => self.class.name) do
@node = attributes
instrument :associations do

View File

@ -254,6 +254,28 @@ class SerializerTest < ActiveModel::TestCase
assert_equal({ :my_blog => { :author => nil } }, serializer.new(blog, :scope => user).as_json)
end
def test_nil_root_object
user = User.new
blog = nil
serializer = Class.new(BlogSerializer) do
root false
end
assert_equal(nil, serializer.new(blog, :scope => user).as_json)
end
def test_custom_root_with_nil_root_object
user = User.new
blog = nil
serializer = Class.new(BlogSerializer) do
root :my_blog
end
assert_equal({ :my_blog => nil }, serializer.new(blog, :scope => user).as_json)
end
def test_false_root
user = User.new
blog = Blog.new