You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> Some of you might be wondering why I didn't choose to make the customized object contain functions, so that `email` can be specified as a function, instead of passing two parameters. This is a **design choice** I stand by, as the cost of calling a function for each property can easily pile up. Instead, most of the time, we can get away with passing a function that generates multiple properties at once. At most, we'll end up with an object and a function for each factory call.
242
242
243
+
### Clearing objects
244
+
245
+
In some cases, we might want to **clear out objects**, to make sure they don't interfere with our tests. This is especially useful when we're counting records or checking relationships, for example.
246
+
247
+
We can add two new methods, `clear` and `clearAll`, to our `Factory` class to handle this. These methods will simply access the **static variables** (`instances`, `indexedInstances` and `getterCache`) of the `Model` class and reset them.
248
+
249
+
```js [src/core/factory.js]
250
+
importModelfrom'#src/core/model.js';
251
+
252
+
exportdefaultclassFactory {
253
+
// ...
254
+
255
+
staticclear(model) {
256
+
Model.instances[model] = [];
257
+
Model.indexedInstances[model] =newMap();
258
+
Model.getterCache[model] = {};
259
+
}
260
+
261
+
staticclearAll() {
262
+
Model.instances= {};
263
+
Model.indexedInstances= {};
264
+
Model.getterCache= {};
265
+
}
266
+
}
267
+
```
268
+
269
+
And here they are in action, clearing instances created by the `PostFactory`.
270
+
271
+
```js
272
+
PostFactory.build();
273
+
Post.all.length; // 1
274
+
Factory.clear('Post');
275
+
Post.all.length; // 0
276
+
```
277
+
243
278
### Convenience methods
244
279
245
280
As you're well aware by this point, convenience methods are a staple of my coding style. I definitely dislike having to find the appropriate factory to call every time I need to create an object. I'd much rather call a method on the `Factory` class itself, specifying the model I want to create.
@@ -671,6 +706,8 @@ export default class Serializer {
671
706
```
672
707
673
708
```js [src/core/factory.js]
709
+
importModelfrom'#src/core/model.js';
710
+
674
711
constsequenceSymbol=Symbol('sequence');
675
712
676
713
constisSequence=value=>
@@ -728,6 +765,18 @@ export default class Factory {
0 commit comments