From 44044fd87a44a17a77e2ede74cb96811e416d940 Mon Sep 17 00:00:00 2001 From: bmac Date: Wed, 14 Oct 2015 05:19:17 -0400 Subject: [PATCH] Deprecate complex objects as an attributes `defaultValue`. They often do not work how a user expects. Closes #3766 --- .jshintrc | 1 + .../ember-data/lib/system/model/attributes.js | 8 ++++- packages/ember-data/tests/unit/model-test.js | 35 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/.jshintrc b/.jshintrc index e1fedd58e0b..9c939529750 100644 --- a/.jshintrc +++ b/.jshintrc @@ -35,6 +35,7 @@ "jQuery", "expectAssertion", "expectDeprecation", + "expectNoDeprecation", "warns", "noWarns", "throws", diff --git a/packages/ember-data/lib/system/model/attributes.js b/packages/ember-data/lib/system/model/attributes.js index 8d720ab8f14..fe00babe6c9 100644 --- a/packages/ember-data/lib/system/model/attributes.js +++ b/packages/ember-data/lib/system/model/attributes.js @@ -226,7 +226,13 @@ function getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue.apply(null, arguments); } else { - return options.defaultValue; + let defaultValue = options.defaultValue; + Ember.deprecate(`Non primitive defaultValues are deprecated because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.`, + typeof defaultValue !== 'object' || defaultValue === null, { + id: 'ds.defaultValue.complex-object', + until: '3.0.0' + }); + return defaultValue; } } diff --git a/packages/ember-data/tests/unit/model-test.js b/packages/ember-data/tests/unit/model-test.js index 7e9a31118c8..b9c7f1c3b99 100644 --- a/packages/ember-data/tests/unit/model-test.js +++ b/packages/ember-data/tests/unit/model-test.js @@ -611,6 +611,41 @@ test("a defaultValue function gets the record, options, and key", function() { get(tag, 'createdAt'); }); +test("a complex object defaultValue is deprecated ", function() { + var Tag = DS.Model.extend({ + tagInfo: DS.attr({ defaultValue: [] }) + }); + var tag; + + var store = createStore({ + tag: Tag + }); + + run(function() { + tag = store.createRecord('tag'); + }); + expectDeprecation(function() { + get(tag, 'tagInfo'); + }, /Non primitive defaultValues are deprecated/); +}); + +test("a null defaultValue is not deprecated", function() { + var Tag = DS.Model.extend({ + tagInfo: DS.attr({ defaultValue: null }) + }); + var tag; + + var store = createStore({ + tag: Tag + }); + + run(function() { + tag = store.createRecord('tag'); + }); + expectNoDeprecation(); + equal(get(tag, 'tagInfo'), null); +}); + test("setting a property to undefined on a newly created record should not impact the current state", function() { var Tag = DS.Model.extend({ name: DS.attr('string')