From 4ca647c3c36ef450cf33532d45112a7bcf7f59d5 Mon Sep 17 00:00:00 2001 From: williamcoates Date: Tue, 22 Nov 2011 12:22:25 +0200 Subject: [PATCH 1/2] Allow finding a model by primary key via App.Model.find(id). --- src/sproutcore-resource.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/sproutcore-resource.js b/src/sproutcore-resource.js index f546088..1480a91 100644 --- a/src/sproutcore-resource.js +++ b/src/sproutcore-resource.js @@ -907,6 +907,13 @@ return this; }, + find: function(id) { + if (SC.none(this.identityMap)) { + return null; + } + return this.identityMap[id]; + }, + // Create an instance of this resource. If `options` includes an // `id`, first check the identity map and return the existing resource // with that ID if found. From bc6cebf795bdf841ea9514004d6c535c379322e3 Mon Sep 17 00:00:00 2001 From: williamcoates Date: Tue, 22 Nov 2011 13:49:16 +0200 Subject: [PATCH 2/2] Implemented basic specs for find, and ensure return null not undefined when no model exists for given id. --- spec/javascripts/resourceSpec.js | 16 +++++++++++++++- src/sproutcore-resource.js | 2 +- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/spec/javascripts/resourceSpec.js b/spec/javascripts/resourceSpec.js index ae65af8..e18a0c5 100644 --- a/spec/javascripts/resourceSpec.js +++ b/spec/javascripts/resourceSpec.js @@ -41,7 +41,7 @@ describe('A Resource instance', function() { it('should not have a URL', function() { expect(model.resourceURL()).toBeUndefined(); - }) + }); }); it('allows setting of properties not in the schema during creation', function() { @@ -80,4 +80,18 @@ describe('A Resource instance', function() { }); }); + describe('finding objects via find', function() { + beforeEach(function() { + model = Model.create({id: 1}); + }); + + it('should return model for the given primary key if it exists', function() { + expect(Model.find(1)).toBe(model); + }); + + it('should return null if no model with the given primary key exists', function() { + expect(Model.find(2)).toBeNull(); + }); + }); + }); diff --git a/src/sproutcore-resource.js b/src/sproutcore-resource.js index 1480a91..24f6d63 100644 --- a/src/sproutcore-resource.js +++ b/src/sproutcore-resource.js @@ -911,7 +911,7 @@ if (SC.none(this.identityMap)) { return null; } - return this.identityMap[id]; + return this.identityMap[id] || null; }, // Create an instance of this resource. If `options` includes an