ember-data-factory-guy 0.7.9 → 0.8.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: b03aa99469ce10e4dd64863b8d36b5daba14be94
4
- data.tar.gz: 7e9e167093d1792f6a146a51e35affc3667ded9a
3
+ metadata.gz: cab48ef500bc4ced2fb01857cca66db95f4c7aea
4
+ data.tar.gz: e574512d0b9706f27a6760454be6467e70c839cf
5
5
  SHA512:
6
- metadata.gz: 9d3b281787780405eb930f2ad26405e7d05fbcced53622efb915a8f6a109dd40d713eb8d7586ecb1bdc947daeb30df95874cf53d05beb58765456db941a612f4
7
- data.tar.gz: 3f239d6ac31b065f73be62f22a264288250dfe66efd942195183551876b7951072f4dc6ec1eeb8ce883332a871220e9d5748a65b62192432d51f59344a11cc11
6
+ metadata.gz: 365a9179282b767ab47d1f7811032f55e3cb90502424e57d26c97ad43122fe3263f6e88e4b764e7a6a230e952e9abb30de54a0f3aca37d60c43c0c501f120973
7
+ data.tar.gz: ab8e3f43429610940df8f8c43083010360264f8f9d322795d7de11d078a0bbb919f195178396206acaa2d8bd4a3a4c8896ee937461dbaebd856386dc10e07555
data/Gruntfile.js CHANGED
@@ -7,12 +7,14 @@ module.exports = function(grunt) {
7
7
  concat: {
8
8
  dist: {
9
9
  src: [
10
+ 'src/prologue.js',
10
11
  'src/sequence.js',
11
12
  'src/model_definition.js',
12
13
  'src/factory_guy.js',
13
14
  'src/store.js',
14
15
  'src/factory_guy_test_mixin.js',
15
- 'bower_components/jquery-mockjax/jquery.mockjax.js'],
16
+ 'src/epilogue.js'
17
+ ],
16
18
  dest: "dist/ember-data-factory-guy.js"
17
19
  },
18
20
  extra: {
data/README.md CHANGED
@@ -9,14 +9,17 @@ of ember-data-factory-guy.
9
9
  - Versions:
10
10
  - 0.6.4 -> ember-data-1.0.0-beta.8 and under
11
11
  - 0.7.1.1 -> ember-data-1.0.0-beta.10
12
- - 0.7.7 -> ember-data-1.0.0-beta.11
13
- - 0.7.7 -> ember-data-1.0.0-beta.12
12
+ - 0.7.9 -> ember-data-1.0.0-beta.11
13
+ - 0.7.9 -> ember-data-1.0.0-beta.12
14
14
 
15
- **For versions ( 0.7.1 -> 0.7.7 ), support for the fixture adapter is currently broken.**
15
+ **For versions ( 0.7.1 -> 0.7.9 ), support for the fixture adapter is currently broken.**
16
16
 
17
- **Version 0.7.7 has many bug fixes that the earlier versions don't have, so hopefully you
18
- can switch to newer version of ember-data and therefore the best ember-data-factory-guy version,
19
- but if not, send me bug report and I will try and go back and fix the older version you are using.**
17
+ *Version 0.7.9 has many bug fixes and improvements that the earlier versions don't have, so
18
+ hopefully you can switch to newer version of ember-data and therefore the best
19
+ ember-data-factory-guy version, but if not, send me bug report and I will try and go back
20
+ and fix the older version you are using.*
21
+
22
+ **Version 0.8.0 introduces amd and commonjs support**
20
23
 
21
24
  ## Using as Gem
22
25
 
@@ -31,7 +34,7 @@ gem 'ember-data-factory-guy', group: test
31
34
  or for particular version:
32
35
 
33
36
  ```ruby
34
- gem 'ember-data-factory-guy', '0.7.7', group: test
37
+ gem 'ember-data-factory-guy', '0.7.9', group: test
35
38
  ```
36
39
 
37
40
  then:
@@ -66,7 +69,7 @@ or for particular version:
66
69
  "dependencies": {
67
70
  "foo-dependency": "latest",
68
71
  "other-foo-dependency": "latest",
69
- "ember-data-factory-guy": "0.7.7"
72
+ "ember-data-factory-guy": "0.7.9"
70
73
  }
71
74
  ```
72
75
 
@@ -606,13 +609,14 @@ and this is already bundled for you when you use the ember-data-factory-guy libr
606
609
  ```
607
610
 
608
611
  ##### handleCreate
612
+
609
613
 
610
614
  *success case is the default*
611
615
 
612
- *Realistically, you will have code in a view action or controller action that will
616
+ Realistically, you will have code in a view action or controller action that will
613
617
  create the record, and setup any associations.
614
618
  Therefore, all you need to pass in to handleCreate are the attributes on the model
615
- that are being tested ( excluding associations .. you don't need those)*
619
+ that are being tested ( excluding associations .. you don't need those)
616
620
 
617
621
  ```javascript
618
622
 
@@ -642,7 +646,8 @@ to a particular user. To mock this createRecord call do this:
642
646
  // set the succeed flag to 'false'
643
647
  testHelper.handleCreate('profile', null, false);
644
648
 
645
- store.createRecord('profile').save() //=> fails
649
+ // when the createRecord on the 'project' is called, it will fail
650
+ store.createRecord('project').save() //=> fails
646
651
 
647
652
  ```
648
653
 
@@ -695,7 +700,7 @@ to a particular user. To mock this createRecord call do this:
695
700
  ````
696
701
 
697
702
 
698
- Here is a sample of what you could do in a view test:
703
+ ##### View test sample
699
704
 
700
705
  ```javascript
701
706
 
@@ -741,12 +746,9 @@ test("Creates new project", function() {
741
746
 
742
747
  actions: {
743
748
  addProject: function (user) {
744
- this.get('controller.store')
745
- .createRecord('project', {
746
- name: this.$('.add-project input').val(),
747
- user: user
748
- })
749
- .save()
749
+ var name = this.$('.add-project input').val();
750
+ var store = this.get('controller.store');
751
+ store.createRecord('project', {name: name, user: user}).save();
750
752
  }
751
753
 
752
754
  */
data/bower.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ember-data-factory-guy",
3
- "version": "0.7.9",
3
+ "version": "0.8.1",
4
4
  "authors": [
5
5
  "Daniel Sudol <dansudol@yahoo.com>",
6
6
  "Opak Alex <opak.alexandr@gmail.com>"
@@ -1,4 +1,6 @@
1
- Sequence = function (fn) {
1
+ (function () {
2
+
3
+ var Sequence = function (fn) {
2
4
  var index = 1;
3
5
  this.next = function () {
4
6
  return fn.call(this, index++);
@@ -7,11 +9,12 @@ Sequence = function (fn) {
7
9
  index = 1;
8
10
  };
9
11
  };
10
- function MissingSequenceError(message) {
12
+
13
+ var MissingSequenceError = function(message) {
11
14
  this.toString = function () {
12
15
  return message;
13
16
  };
14
- }
17
+ };
15
18
  /**
16
19
  A ModelDefinition encapsulates a model's definition
17
20
 
@@ -19,7 +22,7 @@ function MissingSequenceError(message) {
19
22
  @param config
20
23
  @constructor
21
24
  */
22
- ModelDefinition = function (model, config) {
25
+ var ModelDefinition = function (model, config) {
23
26
  var sequences = {};
24
27
  var traits = {};
25
28
  var defaultAttributes = {};
@@ -154,7 +157,7 @@ ModelDefinition = function (model, config) {
154
157
  // initialize
155
158
  parseConfig(config);
156
159
  };
157
- FactoryGuy = {
160
+ var FactoryGuy = {
158
161
  modelDefinitions: {},
159
162
  /**
160
163
  ```javascript
@@ -395,17 +398,8 @@ FactoryGuy = {
395
398
  }
396
399
  return definition.buildList(name, number, traits, opts);
397
400
  },
398
- /**
399
- Unload all models of the given type from the store in the next Ember runloop
400
- */
401
- unloadModel: function (modelType) {
402
- Ember.run(function () {
403
- store.unloadAll(modelType);
404
- });
405
- },
406
- /**
407
- TODO: This is kind of problematic right now .. needs work
408
401
 
402
+ /**
409
403
  Clear model instances from FIXTURES array, and from store cache.
410
404
  Reset the id sequence for the models back to zero.
411
405
  */
@@ -418,8 +412,9 @@ FactoryGuy = {
418
412
  if (store.usingFixtureAdapter()) {
419
413
  modelType.FIXTURES = [];
420
414
  }
421
- this.unloadModel(modelType);
415
+ store.unloadAll(modelType);
422
416
  } catch (e) {
417
+ console.log('resetModels',e)
423
418
  }
424
419
  }
425
420
  },
@@ -447,251 +442,253 @@ FactoryGuy = {
447
442
  }
448
443
  }
449
444
  };
450
- DS.Store.reopen({
451
- /**
452
- @returns {Boolean} true if store's adapter is DS.FixtureAdapter
453
- */
454
- usingFixtureAdapter: function () {
455
- var adapter = this.adapterFor('application');
456
- return adapter instanceof DS.FixtureAdapter;
457
- },
458
- /**
459
- Make new fixture and save to store. If the store is using FixtureAdapter,
460
- will push to FIXTURE array, otherwise will use push method on adapter to load
461
- the record into the store
462
-
463
- @param {String} name fixture name
464
- @param {String} trait optional trait names ( one or more )
465
- @param {Object} opts optional fixture options that will override default fixture values
466
- @returns {Object|DS.Model} json or record depending on the adapter type
467
- */
468
- makeFixture: function () {
469
- var store = this;
470
- var fixture = FactoryGuy.build.apply(FactoryGuy, arguments);
471
- var name = arguments[0];
472
- var modelName = FactoryGuy.lookupModelForFixtureName(name);
473
- var modelType = store.modelFor(modelName);
474
- if (this.usingFixtureAdapter()) {
475
- this.setAssociationsForFixtureAdapter(modelType, modelName, fixture);
476
- return FactoryGuy.pushFixture(modelType, fixture);
477
- } else {
478
- return store.makeModel(modelType, fixture);
479
- }
480
- },
481
- makeModel: function (modelType, fixture) {
482
- var store = this, modelName = store.modelFor(modelType).typeKey, model;
483
- Em.run(function () {
484
- store.findEmbeddedAssociationsForRESTAdapter(modelType, fixture);
485
- if (fixture.type) {
486
- // assuming its polymorphic if there is a type attribute
487
- // is this too bold an assumption?
488
- modelName = fixture.type.underscore();
489
- modelType = store.modelFor(modelName);
445
+ (function () {
446
+ DS.Store.reopen({
447
+ /**
448
+ @returns {Boolean} true if store's adapter is DS.FixtureAdapter
449
+ */
450
+ usingFixtureAdapter: function () {
451
+ var adapter = this.adapterFor('application');
452
+ return adapter instanceof DS.FixtureAdapter;
453
+ },
454
+ /**
455
+ Make new fixture and save to store. If the store is using FixtureAdapter,
456
+ will push to FIXTURE array, otherwise will use push method on adapter to load
457
+ the record into the store
458
+
459
+ @param {String} name fixture name
460
+ @param {String} trait optional trait names ( one or more )
461
+ @param {Object} opts optional fixture options that will override default fixture values
462
+ @returns {Object|DS.Model} json or record depending on the adapter type
463
+ */
464
+ makeFixture: function () {
465
+ var store = this;
466
+ var fixture = FactoryGuy.build.apply(FactoryGuy, arguments);
467
+ var name = arguments[0];
468
+ var modelName = FactoryGuy.lookupModelForFixtureName(name);
469
+ var modelType = store.modelFor(modelName);
470
+ if (this.usingFixtureAdapter()) {
471
+ this.setAssociationsForFixtureAdapter(modelType, modelName, fixture);
472
+ return FactoryGuy.pushFixture(modelType, fixture);
473
+ } else {
474
+ return store.makeModel(modelType, fixture);
490
475
  }
491
- model = store.push(modelName, fixture);
492
- store.setAssociationsForRESTAdapter(modelType, modelName, model);
493
- });
494
- return model;
495
- },
496
- /**
497
- Make a list of Fixtures
498
-
499
- @param {String} name name of fixture
500
- @param {Number} number number to create
501
- @param {Object} options fixture options
502
- @returns {Array} list of json fixtures or records depending on the adapter type
503
- */
504
- makeList: function () {
505
- var arr = [];
506
- var number = arguments[1];
507
- for (var i = 0; i < number; i++) {
508
- arr.push(this.makeFixture.apply(this, arguments));
509
- }
510
- return arr;
511
- },
512
- /**
513
- Set the hasMany and belongsTo associations for FixtureAdapter.
514
-
515
- For example, assuming a user hasMany projects, if you make a project,
516
- then a user with that project in the users list of project, then this method
517
- will go back and set the user.id on each project that the user hasMany of,
518
- so that the project now has the belongsTo user association setup.
519
- As in this scenario:
520
-
521
- ```js
522
- var projectJson = store.makeFixture('project');
523
- var userJson = store.makeFixture('user', {projects: [projectJson]});
524
- ```
525
-
526
- Or if you make a project with a user, then set this project in
527
- the users list of 'projects' it hasMany of. As in this scenario:
528
-
529
- ```js
530
- var userJson = store.makeFixture('user');
531
- var projectJson = store.makeFixture('project', {user: userJson});
532
- ```
533
-
534
- @param {DS.Model} modelType model type like User
535
- @param {String} modelName model name like 'user'
536
- @param {Object} fixture to check for needed association assignments
537
- */
538
- setAssociationsForFixtureAdapter: function (modelType, modelName, fixture) {
539
- var self = this;
540
- var adapter = this.adapterFor('application');
541
- Ember.get(modelType, 'relationshipsByName').forEach(function (relationship, name) {
542
- if (relationship.kind == 'hasMany') {
543
- var hasManyRelation = fixture[relationship.key];
544
- if (hasManyRelation) {
545
- $.each(fixture[relationship.key], function (index, object) {
546
- // used to require that the relationship was set by id,
547
- // but now, you can set it as the json object, and this will
548
- // normalize that back to the id
549
- var id = object;
550
- if (Ember.typeOf(object) == 'object') {
551
- id = object.id;
552
- hasManyRelation[index] = id;
553
- }
554
- var hasManyfixtures = adapter.fixturesForType(relationship.type);
555
- var fixture = adapter.findFixtureById(hasManyfixtures, id);
556
- fixture[modelName] = fixture.id;
557
- });
476
+ },
477
+ makeModel: function (modelType, fixture) {
478
+ var store = this, modelName = store.modelFor(modelType).typeKey, model;
479
+ Em.run(function () {
480
+ store.findEmbeddedAssociationsForRESTAdapter(modelType, fixture);
481
+ if (fixture.type) {
482
+ // assuming its polymorphic if there is a type attribute
483
+ // is this too bold an assumption?
484
+ modelName = fixture.type.underscore();
485
+ modelType = store.modelFor(modelName);
558
486
  }
487
+ model = store.push(modelName, fixture);
488
+ store.setAssociationsForRESTAdapter(modelType, modelName, model);
489
+ });
490
+ return model;
491
+ },
492
+ /**
493
+ Make a list of Fixtures
494
+
495
+ @param {String} name name of fixture
496
+ @param {Number} number number to create
497
+ @param {Object} options fixture options
498
+ @returns {Array} list of json fixtures or records depending on the adapter type
499
+ */
500
+ makeList: function () {
501
+ var arr = [];
502
+ var number = arguments[1];
503
+ for (var i = 0; i < number; i++) {
504
+ arr.push(this.makeFixture.apply(this, arguments));
559
505
  }
560
- if (relationship.kind == 'belongsTo') {
561
- var belongsToRecord = fixture[relationship.key];
562
- if (belongsToRecord) {
563
- if (typeof belongsToRecord == 'object') {
564
- FactoryGuy.pushFixture(relationship.type, belongsToRecord);
565
- fixture[relationship.key] = belongsToRecord.id;
566
- }
567
- var hasManyName = self.findHasManyRelationshipNameForFixtureAdapter(relationship.type, relationship.parentType);
568
- var belongsToFixtures = adapter.fixturesForType(relationship.type);
569
- var belongsTofixture = adapter.findFixtureById(belongsToFixtures, fixture[relationship.key]);
570
- if (!belongsTofixture[hasManyName]) {
571
- belongsTofixture[hasManyName] = [];
506
+ return arr;
507
+ },
508
+ /**
509
+ Set the hasMany and belongsTo associations for FixtureAdapter.
510
+
511
+ For example, assuming a user hasMany projects, if you make a project,
512
+ then a user with that project in the users list of project, then this method
513
+ will go back and set the user.id on each project that the user hasMany of,
514
+ so that the project now has the belongsTo user association setup.
515
+ As in this scenario:
516
+
517
+ ```js
518
+ var projectJson = store.makeFixture('project');
519
+ var userJson = store.makeFixture('user', {projects: [projectJson]});
520
+ ```
521
+
522
+ Or if you make a project with a user, then set this project in
523
+ the users list of 'projects' it hasMany of. As in this scenario:
524
+
525
+ ```js
526
+ var userJson = store.makeFixture('user');
527
+ var projectJson = store.makeFixture('project', {user: userJson});
528
+ ```
529
+
530
+ @param {DS.Model} modelType model type like User
531
+ @param {String} modelName model name like 'user'
532
+ @param {Object} fixture to check for needed association assignments
533
+ */
534
+ setAssociationsForFixtureAdapter: function (modelType, modelName, fixture) {
535
+ var self = this;
536
+ var adapter = this.adapterFor('application');
537
+ Ember.get(modelType, 'relationshipsByName').forEach(function (relationship, name) {
538
+ if (relationship.kind == 'hasMany') {
539
+ var hasManyRelation = fixture[relationship.key];
540
+ if (hasManyRelation) {
541
+ $.each(fixture[relationship.key], function (index, object) {
542
+ // used to require that the relationship was set by id,
543
+ // but now, you can set it as the json object, and this will
544
+ // normalize that back to the id
545
+ var id = object;
546
+ if (Ember.typeOf(object) == 'object') {
547
+ id = object.id;
548
+ hasManyRelation[index] = id;
549
+ }
550
+ var hasManyfixtures = adapter.fixturesForType(relationship.type);
551
+ var fixture = adapter.findFixtureById(hasManyfixtures, id);
552
+ fixture[modelName] = fixture.id;
553
+ });
572
554
  }
573
- belongsTofixture[hasManyName].push(fixture.id);
574
555
  }
575
- }
576
- });
577
- },
578
- /**
579
- Before pushing the fixture to the store, do some preprocessing. Descend into the tree
580
- of object data, and convert child objects to record instances recursively.
581
-
582
- If its a belongs to association, and the fixture has an object there,
583
- then push that model to the store and set the id of that new model
584
- as the attribute value in the fixture
585
-
586
- @param modelType
587
- @param fixture
588
- */
589
- findEmbeddedAssociationsForRESTAdapter: function (modelType, fixture) {
590
- var store = this;
591
- Ember.get(modelType, 'relationshipsByName').forEach(function (relationship, name) {
592
- if (relationship.kind == 'belongsTo') {
593
- var belongsToRecord = fixture[relationship.key];
594
- if (Ember.typeOf(belongsToRecord) == 'object') {
595
- store.findEmbeddedAssociationsForRESTAdapter(relationship.type, belongsToRecord);
596
- belongsToRecord = store.push(relationship.type, belongsToRecord);
597
- fixture[relationship.key] = belongsToRecord;
556
+ if (relationship.kind == 'belongsTo') {
557
+ var belongsToRecord = fixture[relationship.key];
558
+ if (belongsToRecord) {
559
+ if (typeof belongsToRecord == 'object') {
560
+ FactoryGuy.pushFixture(relationship.type, belongsToRecord);
561
+ fixture[relationship.key] = belongsToRecord.id;
562
+ }
563
+ var hasManyName = self.findHasManyRelationshipNameForFixtureAdapter(relationship.type, relationship.parentType);
564
+ var belongsToFixtures = adapter.fixturesForType(relationship.type);
565
+ var belongsTofixture = adapter.findFixtureById(belongsToFixtures, fixture[relationship.key]);
566
+ if (!belongsTofixture[hasManyName]) {
567
+ belongsTofixture[hasManyName] = [];
568
+ }
569
+ belongsTofixture[hasManyName].push(fixture.id);
570
+ }
598
571
  }
599
- }
600
- if (relationship.kind == 'hasMany') {
601
- var hasManyRecords = fixture[relationship.key];
602
- if (Ember.typeOf(hasManyRecords) == 'array') {
603
- if (Ember.typeOf(hasManyRecords[0]) == 'object') {
604
- var records = Em.A();
605
- hasManyRecords.map(function (object) {
606
- store.findEmbeddedAssociationsForRESTAdapter(relationship.type, object);
607
- var record = store.push(relationship.type, object);
608
- records.push(record);
609
- return record;
610
- });
611
- fixture[relationship.key] = records;
572
+ });
573
+ },
574
+ /**
575
+ Before pushing the fixture to the store, do some preprocessing. Descend into the tree
576
+ of object data, and convert child objects to record instances recursively.
577
+
578
+ If its a belongs to association, and the fixture has an object there,
579
+ then push that model to the store and set the id of that new model
580
+ as the attribute value in the fixture
581
+
582
+ @param modelType
583
+ @param fixture
584
+ */
585
+ findEmbeddedAssociationsForRESTAdapter: function (modelType, fixture) {
586
+ var store = this;
587
+ Ember.get(modelType, 'relationshipsByName').forEach(function (relationship, name) {
588
+ if (relationship.kind == 'belongsTo') {
589
+ var belongsToRecord = fixture[relationship.key];
590
+ if (Ember.typeOf(belongsToRecord) == 'object') {
591
+ store.findEmbeddedAssociationsForRESTAdapter(relationship.type, belongsToRecord);
592
+ belongsToRecord = store.push(relationship.type, belongsToRecord);
593
+ fixture[relationship.key] = belongsToRecord;
612
594
  }
613
595
  }
614
- }
615
- });
616
- },
617
- /**
618
- For the REST type models:
619
-
620
- For example if a user hasMany projects, then set the user
621
- on each project that the user hasMany of, so that the project
622
- now has the belongsTo user association setup. As in this scenario:
623
-
624
- ```js
625
- var project = store.makeFixture('project');
626
- var user = store.makeFixture('user', {projects: [project]});
627
- ```
628
-
629
- Or if you make a user, then a project with that user, then set the project
630
- in the users list of 'projects' it hasMany of. As in this scenario:
631
-
632
- ```js
633
- var user = store.makeFixture('user');
634
- var project = store.makeFixture('project', {user: user});
635
- ```
636
-
637
- NOTE:
638
- As of ember-data-1.0.0-beta.10 and ember-data-1.0.0-beta.12,
639
- this method is only needed because the belongsTo is not assigned when
640
- there is a self referential polymorphic has many association.
641
-
642
- @param {DS.Model} modelType model type like 'User'
643
- @param {String} modelName model name like 'user'
644
- @param {DS.Model} model model to check for needed association assignments
645
- */
646
- setAssociationsForRESTAdapter: function (modelType, modelName, model) {
647
- var self = this;
648
- Ember.get(modelType, 'relationshipsByName').forEach(function (relationship, name) {
649
- if (relationship.kind == 'hasMany') {
650
- var children = model.get(name) || [];
651
- children.forEach(function (child) {
652
- var belongsToName = self.findRelationshipName('belongsTo', child.constructor, model);
653
- if (belongsToName) {
654
- child.set(belongsToName, model);
596
+ if (relationship.kind == 'hasMany') {
597
+ var hasManyRecords = fixture[relationship.key];
598
+ if (Ember.typeOf(hasManyRecords) == 'array') {
599
+ if (Ember.typeOf(hasManyRecords[0]) == 'object') {
600
+ var records = Em.A();
601
+ hasManyRecords.map(function (object) {
602
+ store.findEmbeddedAssociationsForRESTAdapter(relationship.type, object);
603
+ var record = store.push(relationship.type, object);
604
+ records.push(record);
605
+ return record;
606
+ });
607
+ fixture[relationship.key] = records;
608
+ }
655
609
  }
656
- });
657
- }
658
- });
659
- },
660
- findRelationshipName: function (kind, belongToModelType, childModel) {
661
- var relationshipName;
662
- Ember.get(belongToModelType, 'relationshipsByName').forEach(function (relationship, name) {
663
- if (relationship.kind == kind && childModel instanceof relationship.type) {
664
- relationshipName = relationship.key;
665
- }
666
- });
667
- return relationshipName;
668
- },
669
- findHasManyRelationshipNameForFixtureAdapter: function (belongToModelType, childModelType) {
670
- var relationshipName;
671
- Ember.get(belongToModelType, 'relationshipsByName').forEach(function (relationship, name) {
672
- if (relationship.kind == 'hasMany' && childModelType == relationship.type) {
673
- relationshipName = relationship.key;
610
+ }
611
+ });
612
+ },
613
+ /**
614
+ For the REST type models:
615
+
616
+ For example if a user hasMany projects, then set the user
617
+ on each project that the user hasMany of, so that the project
618
+ now has the belongsTo user association setup. As in this scenario:
619
+
620
+ ```js
621
+ var project = store.makeFixture('project');
622
+ var user = store.makeFixture('user', {projects: [project]});
623
+ ```
624
+
625
+ Or if you make a user, then a project with that user, then set the project
626
+ in the users list of 'projects' it hasMany of. As in this scenario:
627
+
628
+ ```js
629
+ var user = store.makeFixture('user');
630
+ var project = store.makeFixture('project', {user: user});
631
+ ```
632
+
633
+ NOTE:
634
+ As of ember-data-1.0.0-beta.10 and ember-data-1.0.0-beta.12,
635
+ this method is only needed because the belongsTo is not assigned when
636
+ there is a self referential polymorphic has many association.
637
+
638
+ @param {DS.Model} modelType model type like 'User'
639
+ @param {String} modelName model name like 'user'
640
+ @param {DS.Model} model model to check for needed association assignments
641
+ */
642
+ setAssociationsForRESTAdapter: function (modelType, modelName, model) {
643
+ var self = this;
644
+ Ember.get(modelType, 'relationshipsByName').forEach(function (relationship, name) {
645
+ if (relationship.kind == 'hasMany') {
646
+ var children = model.get(name) || [];
647
+ children.forEach(function (child) {
648
+ var belongsToName = self.findRelationshipName('belongsTo', child.constructor, model);
649
+ if (belongsToName) {
650
+ child.set(belongsToName, model);
651
+ }
652
+ });
653
+ }
654
+ });
655
+ },
656
+ findRelationshipName: function (kind, belongToModelType, childModel) {
657
+ var relationshipName;
658
+ Ember.get(belongToModelType, 'relationshipsByName').forEach(function (relationship, name) {
659
+ if (relationship.kind == kind && childModel instanceof relationship.type) {
660
+ relationshipName = relationship.key;
661
+ }
662
+ });
663
+ return relationshipName;
664
+ },
665
+ findHasManyRelationshipNameForFixtureAdapter: function (belongToModelType, childModelType) {
666
+ var relationshipName;
667
+ Ember.get(belongToModelType, 'relationshipsByName').forEach(function (relationship, name) {
668
+ if (relationship.kind == 'hasMany' && childModelType == relationship.type) {
669
+ relationshipName = relationship.key;
670
+ }
671
+ });
672
+ return relationshipName;
673
+ },
674
+ /**
675
+ Adding a pushPayload for FixtureAdapter, but using the original with
676
+ other adapters that support pushPayload.
677
+
678
+ @param {String} type
679
+ @param {Object} payload
680
+ */
681
+ pushPayload: function (type, payload) {
682
+ if (this.usingFixtureAdapter()) {
683
+ var model = this.modelFor(modelName);
684
+ FactoryGuy.pushFixture(model, payload);
685
+ } else {
686
+ this._super(type, payload);
674
687
  }
675
- });
676
- return relationshipName;
677
- },
678
- /**
679
- Adding a pushPayload for FixtureAdapter, but using the original with
680
- other adapters that support pushPayload.
681
-
682
- @param {String} type
683
- @param {Object} payload
684
- */
685
- pushPayload: function (type, payload) {
686
- if (this.usingFixtureAdapter()) {
687
- var model = this.modelFor(modelName);
688
- FactoryGuy.pushFixture(model, payload);
689
- } else {
690
- this._super(type, payload);
691
688
  }
692
- }
693
- });
694
- FactoryGuyTestMixin = Em.Mixin.create({
689
+ });
690
+ })();
691
+ var FactoryGuyTestMixin = Em.Mixin.create({
695
692
  // Pass in the app root, which typically is App.
696
693
  setup: function (app) {
697
694
  this.set('container', app.__container__);
@@ -854,695 +851,28 @@ FactoryGuyTestMixin = Em.Mixin.create({
854
851
  }
855
852
  });
856
853
 
857
- /*!
858
- * MockJax - jQuery Plugin to Mock Ajax requests
859
- *
860
- * Version: 1.6.1
861
- * Released:
862
- * Home: https://github.com/jakerella/jquery-mockjax
863
- * Author: Jonathan Sharp (http://jdsharp.com)
864
- * License: MIT,GPL
865
- *
866
- * Copyright (c) 2014 appendTo, Jordan Kasper
867
- * NOTE: This repository was taken over by Jordan Kasper (@jakerella) October, 2014
868
- *
869
- * Dual licensed under the MIT or GPL licenses.
870
- * http://opensource.org/licenses/MIT OR http://www.gnu.org/licenses/gpl-2.0.html
871
- */
872
- (function($) {
873
- var _ajax = $.ajax,
874
- mockHandlers = [],
875
- mockedAjaxCalls = [],
876
- unmockedAjaxCalls = [],
877
- CALLBACK_REGEX = /=\?(&|$)/,
878
- jsc = (new Date()).getTime();
879
-
880
-
881
- // Parse the given XML string.
882
- function parseXML(xml) {
883
- if ( window.DOMParser == undefined && window.ActiveXObject ) {
884
- DOMParser = function() { };
885
- DOMParser.prototype.parseFromString = function( xmlString ) {
886
- var doc = new ActiveXObject('Microsoft.XMLDOM');
887
- doc.async = 'false';
888
- doc.loadXML( xmlString );
889
- return doc;
890
- };
891
- }
892
-
893
- try {
894
- var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
895
- if ( $.isXMLDoc( xmlDoc ) ) {
896
- var err = $('parsererror', xmlDoc);
897
- if ( err.length == 1 ) {
898
- throw new Error('Error: ' + $(xmlDoc).text() );
899
- }
900
- } else {
901
- throw new Error('Unable to parse XML');
902
- }
903
- return xmlDoc;
904
- } catch( e ) {
905
- var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
906
- $(document).trigger('xmlParseError', [ msg ]);
907
- return undefined;
908
- }
909
- }
854
+ FactoryGuy.testMixin = FactoryGuyTestMixin;
855
+ FactoryGuy.sequence = Sequence;
856
+ FactoryGuy.sequence.missingSequenceError = MissingSequenceError;
910
857
 
911
- // Check if the data field on the mock handler and the request match. This
912
- // can be used to restrict a mock handler to being used only when a certain
913
- // set of data is passed to it.
914
- function isMockDataEqual( mock, live ) {
915
- var identical = true;
916
- // Test for situations where the data is a querystring (not an object)
917
- if (typeof live === 'string') {
918
- // Querystring may be a regex
919
- return $.isFunction( mock.test ) ? mock.test(live) : mock == live;
920
- }
921
- $.each(mock, function(k) {
922
- if ( live[k] === undefined ) {
923
- identical = false;
924
- return identical;
925
- } else {
926
- if ( typeof live[k] === 'object' && live[k] !== null ) {
927
- if ( identical && $.isArray( live[k] ) ) {
928
- identical = $.isArray( mock[k] ) && live[k].length === mock[k].length;
929
- }
930
- identical = identical && isMockDataEqual(mock[k], live[k]);
931
- } else {
932
- if ( mock[k] && $.isFunction( mock[k].test ) ) {
933
- identical = identical && mock[k].test(live[k]);
934
- } else {
935
- identical = identical && ( mock[k] == live[k] );
936
- }
937
- }
938
- }
939
- });
940
-
941
- return identical;
942
- }
943
-
944
- // See if a mock handler property matches the default settings
945
- function isDefaultSetting(handler, property) {
946
- return handler[property] === $.mockjaxSettings[property];
858
+ // CommonJS module
859
+ if (typeof exports !== 'undefined') {
860
+ if (typeof module !== 'undefined' && module.exports) {
861
+ exports = module.exports = FactoryGuy;
947
862
  }
863
+ exports.FactoryGuy = FactoryGuy;
864
+ }
948
865
 
949
- // Check the given handler should mock the given request
950
- function getMockForRequest( handler, requestSettings ) {
951
- // If the mock was registered with a function, let the function decide if we
952
- // want to mock this request
953
- if ( $.isFunction(handler) ) {
954
- return handler( requestSettings );
955
- }
956
-
957
- // Inspect the URL of the request and check if the mock handler's url
958
- // matches the url for this ajax request
959
- if ( $.isFunction(handler.url.test) ) {
960
- // The user provided a regex for the url, test it
961
- if ( !handler.url.test( requestSettings.url ) ) {
962
- return null;
963
- }
964
- } else {
965
- // Look for a simple wildcard '*' or a direct URL match
966
- var star = handler.url.indexOf('*');
967
- if (handler.url !== requestSettings.url && star === -1 ||
968
- !new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace(/\*/g, '.+')).test(requestSettings.url)) {
969
- return null;
970
- }
971
- }
972
-
973
- // Inspect the data submitted in the request (either POST body or GET query string)
974
- if ( handler.data ) {
975
- if ( ! requestSettings.data || !isMockDataEqual(handler.data, requestSettings.data) ) {
976
- // They're not identical, do not mock this request
977
- return null;
978
- }
979
- }
980
- // Inspect the request type
981
- if ( handler && handler.type &&
982
- handler.type.toLowerCase() != requestSettings.type.toLowerCase() ) {
983
- // The request type doesn't match (GET vs. POST)
984
- return null;
985
- }
986
-
987
- return handler;
988
- }
989
-
990
- function parseResponseTimeOpt(responseTime) {
991
- if ($.isArray(responseTime)) {
992
- var min = responseTime[0];
993
- var max = responseTime[1];
994
- return (typeof min === 'number' && typeof max === 'number') ? Math.floor(Math.random() * (max - min)) + min : null;
995
- } else {
996
- return (typeof responseTime === 'number') ? responseTime: null;
997
- }
998
- }
999
-
1000
- // Process the xhr objects send operation
1001
- function _xhrSend(mockHandler, requestSettings, origSettings) {
1002
-
1003
- // This is a substitute for < 1.4 which lacks $.proxy
1004
- var process = (function(that) {
1005
- return function() {
1006
- return (function() {
1007
- // The request has returned
1008
- this.status = mockHandler.status;
1009
- this.statusText = mockHandler.statusText;
1010
- this.readyState = 1;
1011
-
1012
- var finishRequest = function () {
1013
- this.readyState = 4;
1014
-
1015
- var onReady;
1016
- // Copy over our mock to our xhr object before passing control back to
1017
- // jQuery's onreadystatechange callback
1018
- if ( requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' ) ) {
1019
- this.responseText = JSON.stringify(mockHandler.responseText);
1020
- } else if ( requestSettings.dataType == 'xml' ) {
1021
- if ( typeof mockHandler.responseXML == 'string' ) {
1022
- this.responseXML = parseXML(mockHandler.responseXML);
1023
- //in jQuery 1.9.1+, responseXML is processed differently and relies on responseText
1024
- this.responseText = mockHandler.responseXML;
1025
- } else {
1026
- this.responseXML = mockHandler.responseXML;
1027
- }
1028
- } else if (typeof mockHandler.responseText === 'object' && mockHandler.responseText !== null) {
1029
- // since jQuery 1.9 responseText type has to match contentType
1030
- mockHandler.contentType = 'application/json';
1031
- this.responseText = JSON.stringify(mockHandler.responseText);
1032
- } else {
1033
- this.responseText = mockHandler.responseText;
1034
- }
1035
- if( typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string' ) {
1036
- this.status = mockHandler.status;
1037
- }
1038
- if( typeof mockHandler.statusText === "string") {
1039
- this.statusText = mockHandler.statusText;
1040
- }
1041
- // jQuery 2.0 renamed onreadystatechange to onload
1042
- onReady = this.onreadystatechange || this.onload;
1043
-
1044
- // jQuery < 1.4 doesn't have onreadystate change for xhr
1045
- if ( $.isFunction( onReady ) ) {
1046
- if( mockHandler.isTimeout) {
1047
- this.status = -1;
1048
- }
1049
- onReady.call( this, mockHandler.isTimeout ? 'timeout' : undefined );
1050
- } else if ( mockHandler.isTimeout ) {
1051
- // Fix for 1.3.2 timeout to keep success from firing.
1052
- this.status = -1;
1053
- }
1054
- };
1055
-
1056
- // We have an executable function, call it to give
1057
- // the mock handler a chance to update it's data
1058
- if ( $.isFunction(mockHandler.response) ) {
1059
- // Wait for it to finish
1060
- if ( mockHandler.response.length === 2 ) {
1061
- mockHandler.response(origSettings, function () {
1062
- finishRequest.call(that);
1063
- });
1064
- return;
1065
- } else {
1066
- mockHandler.response(origSettings);
1067
- }
1068
- }
1069
-
1070
- finishRequest.call(that);
1071
- }).apply(that);
1072
- };
1073
- })(this);
1074
-
1075
- if ( mockHandler.proxy ) {
1076
- // We're proxying this request and loading in an external file instead
1077
- _ajax({
1078
- global: false,
1079
- url: mockHandler.proxy,
1080
- type: mockHandler.proxyType,
1081
- data: mockHandler.data,
1082
- dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType,
1083
- complete: function(xhr) {
1084
- mockHandler.responseXML = xhr.responseXML;
1085
- mockHandler.responseText = xhr.responseText;
1086
- // Don't override the handler status/statusText if it's specified by the config
1087
- if (isDefaultSetting(mockHandler, 'status')) {
1088
- mockHandler.status = xhr.status;
1089
- }
1090
- if (isDefaultSetting(mockHandler, 'statusText')) {
1091
- mockHandler.statusText = xhr.statusText;
1092
- }
1093
- this.responseTimer = setTimeout(process, parseResponseTimeOpt(mockHandler.responseTime) || 0);
1094
- }
1095
- });
1096
- } else {
1097
- // type == 'POST' || 'GET' || 'DELETE'
1098
- if ( requestSettings.async === false ) {
1099
- // TODO: Blocking delay
1100
- process();
1101
- } else {
1102
- this.responseTimer = setTimeout(process, parseResponseTimeOpt(mockHandler.responseTime) || 50);
1103
- }
1104
- }
1105
- }
1106
-
1107
- // Construct a mocked XHR Object
1108
- function xhr(mockHandler, requestSettings, origSettings, origHandler) {
1109
- // Extend with our default mockjax settings
1110
- mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);
1111
-
1112
- if (typeof mockHandler.headers === 'undefined') {
1113
- mockHandler.headers = {};
1114
- }
1115
- if (typeof requestSettings.headers === 'undefined') {
1116
- requestSettings.headers = {};
1117
- }
1118
- if ( mockHandler.contentType ) {
1119
- mockHandler.headers['content-type'] = mockHandler.contentType;
1120
- }
1121
-
1122
- return {
1123
- status: mockHandler.status,
1124
- statusText: mockHandler.statusText,
1125
- readyState: 1,
1126
- open: function() { },
1127
- send: function() {
1128
- origHandler.fired = true;
1129
- _xhrSend.call(this, mockHandler, requestSettings, origSettings);
1130
- },
1131
- abort: function() {
1132
- clearTimeout(this.responseTimer);
1133
- },
1134
- setRequestHeader: function(header, value) {
1135
- requestSettings.headers[header] = value;
1136
- },
1137
- getResponseHeader: function(header) {
1138
- // 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
1139
- if ( mockHandler.headers && mockHandler.headers[header] ) {
1140
- // Return arbitrary headers
1141
- return mockHandler.headers[header];
1142
- } else if ( header.toLowerCase() == 'last-modified' ) {
1143
- return mockHandler.lastModified || (new Date()).toString();
1144
- } else if ( header.toLowerCase() == 'etag' ) {
1145
- return mockHandler.etag || '';
1146
- } else if ( header.toLowerCase() == 'content-type' ) {
1147
- return mockHandler.contentType || 'text/plain';
1148
- }
1149
- },
1150
- getAllResponseHeaders: function() {
1151
- var headers = '';
1152
- // since jQuery 1.9 responseText type has to match contentType
1153
- if (mockHandler.contentType) {
1154
- mockHandler.headers['Content-Type'] = mockHandler.contentType;
1155
- }
1156
- $.each(mockHandler.headers, function(k, v) {
1157
- headers += k + ': ' + v + "\n";
1158
- });
1159
- return headers;
1160
- }
1161
- };
1162
- }
1163
-
1164
- // Process a JSONP mock request.
1165
- function processJsonpMock( requestSettings, mockHandler, origSettings ) {
1166
- // Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
1167
- // because there isn't an easy hook for the cross domain script tag of jsonp
1168
-
1169
- processJsonpUrl( requestSettings );
1170
-
1171
- requestSettings.dataType = "json";
1172
- if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
1173
- createJsonpCallback(requestSettings, mockHandler, origSettings);
1174
-
1175
- // We need to make sure
1176
- // that a JSONP style response is executed properly
1177
-
1178
- var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
1179
- parts = rurl.exec( requestSettings.url ),
1180
- remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
1181
-
1182
- requestSettings.dataType = "script";
1183
- if(requestSettings.type.toUpperCase() === "GET" && remote ) {
1184
- var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );
1185
-
1186
- // Check if we are supposed to return a Deferred back to the mock call, or just
1187
- // signal success
1188
- if(newMockReturn) {
1189
- return newMockReturn;
1190
- } else {
1191
- return true;
1192
- }
1193
- }
1194
- }
1195
- return null;
1196
- }
1197
-
1198
- // Append the required callback parameter to the end of the request URL, for a JSONP request
1199
- function processJsonpUrl( requestSettings ) {
1200
- if ( requestSettings.type.toUpperCase() === "GET" ) {
1201
- if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {
1202
- requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +
1203
- (requestSettings.jsonp || "callback") + "=?";
1204
- }
1205
- } else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {
1206
- requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";
1207
- }
1208
- }
1209
-
1210
- // Process a JSONP request by evaluating the mocked response text
1211
- function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
1212
- // Synthesize the mock request for adding a script tag
1213
- var callbackContext = origSettings && origSettings.context || requestSettings,
1214
- newMock = null;
1215
-
1216
-
1217
- // If the response handler on the moock is a function, call it
1218
- if ( mockHandler.response && $.isFunction(mockHandler.response) ) {
1219
- mockHandler.response(origSettings);
1220
- } else {
1221
-
1222
- // Evaluate the responseText javascript in a global context
1223
- if( typeof mockHandler.responseText === 'object' ) {
1224
- $.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');
1225
- } else {
1226
- $.globalEval( '(' + mockHandler.responseText + ')');
1227
- }
1228
- }
1229
-
1230
- // Successful response
1231
- setTimeout(function() {
1232
- jsonpSuccess( requestSettings, callbackContext, mockHandler );
1233
- jsonpComplete( requestSettings, callbackContext, mockHandler );
1234
- }, parseResponseTimeOpt(mockHandler.responseTime) || 0);
1235
-
1236
- // If we are running under jQuery 1.5+, return a deferred object
1237
- if($.Deferred){
1238
- newMock = new $.Deferred();
1239
- if(typeof mockHandler.responseText == "object"){
1240
- newMock.resolveWith( callbackContext, [mockHandler.responseText] );
1241
- }
1242
- else{
1243
- newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );
1244
- }
1245
- }
1246
- return newMock;
1247
- }
1248
-
1249
-
1250
- // Create the required JSONP callback function for the request
1251
- function createJsonpCallback( requestSettings, mockHandler, origSettings ) {
1252
- var callbackContext = origSettings && origSettings.context || requestSettings;
1253
- var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);
1254
-
1255
- // Replace the =? sequence both in the query string and the data
1256
- if ( requestSettings.data ) {
1257
- requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");
1258
- }
1259
-
1260
- requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");
1261
-
1262
-
1263
- // Handle JSONP-style loading
1264
- window[ jsonp ] = window[ jsonp ] || function( tmp ) {
1265
- data = tmp;
1266
- jsonpSuccess( requestSettings, callbackContext, mockHandler );
1267
- jsonpComplete( requestSettings, callbackContext, mockHandler );
1268
- // Garbage collect
1269
- window[ jsonp ] = undefined;
1270
-
1271
- try {
1272
- delete window[ jsonp ];
1273
- } catch(e) {}
1274
-
1275
- if ( head ) {
1276
- head.removeChild( script );
1277
- }
1278
- };
1279
- }
1280
-
1281
- // The JSONP request was successful
1282
- function jsonpSuccess(requestSettings, callbackContext, mockHandler) {
1283
- // If a local callback was specified, fire it and pass it the data
1284
- if ( requestSettings.success ) {
1285
- requestSettings.success.call( callbackContext, mockHandler.responseText || "", status, {} );
1286
- }
1287
-
1288
- // Fire the global callback
1289
- if ( requestSettings.global ) {
1290
- (requestSettings.context ? $(requestSettings.context) : $.event).trigger("ajaxSuccess", [{}, requestSettings]);
1291
- }
1292
- }
1293
-
1294
- // The JSONP request was completed
1295
- function jsonpComplete(requestSettings, callbackContext) {
1296
- // Process result
1297
- if ( requestSettings.complete ) {
1298
- requestSettings.complete.call( callbackContext, {} , status );
1299
- }
1300
-
1301
- // The request was completed
1302
- if ( requestSettings.global ) {
1303
- (requestSettings.context ? $(requestSettings.context) : $.event).trigger("ajaxComplete", [{}, requestSettings]);
1304
- }
1305
-
1306
- // Handle the global AJAX counter
1307
- if ( requestSettings.global && ! --$.active ) {
1308
- $.event.trigger( "ajaxStop" );
1309
- }
1310
- }
1311
-
1312
-
1313
- // The core $.ajax replacement.
1314
- function handleAjax( url, origSettings ) {
1315
- var mockRequest, requestSettings, mockHandler, overrideCallback;
1316
-
1317
- // If url is an object, simulate pre-1.5 signature
1318
- if ( typeof url === "object" ) {
1319
- origSettings = url;
1320
- url = undefined;
1321
- } else {
1322
- // work around to support 1.5 signature
1323
- origSettings = origSettings || {};
1324
- origSettings.url = url;
1325
- }
1326
-
1327
- // Extend the original settings for the request
1328
- requestSettings = $.extend(true, {}, $.ajaxSettings, origSettings);
1329
-
1330
- // Generic function to override callback methods for use with
1331
- // callback options (onAfterSuccess, onAfterError, onAfterComplete)
1332
- overrideCallback = function(action, mockHandler) {
1333
- var origHandler = origSettings[action.toLowerCase()];
1334
- return function() {
1335
- if ( $.isFunction(origHandler) ) {
1336
- origHandler.apply(this, [].slice.call(arguments));
1337
- }
1338
- mockHandler['onAfter' + action]();
1339
- };
1340
- };
1341
-
1342
- // Iterate over our mock handlers (in registration order) until we find
1343
- // one that is willing to intercept the request
1344
- for(var k = 0; k < mockHandlers.length; k++) {
1345
- if ( !mockHandlers[k] ) {
1346
- continue;
1347
- }
1348
-
1349
- mockHandler = getMockForRequest( mockHandlers[k], requestSettings );
1350
- if(!mockHandler) {
1351
- // No valid mock found for this request
1352
- continue;
1353
- }
1354
-
1355
- mockedAjaxCalls.push(requestSettings);
1356
-
1357
- // If logging is enabled, log the mock to the console
1358
- $.mockjaxSettings.log( mockHandler, requestSettings );
1359
-
1360
-
1361
- if ( requestSettings.dataType && requestSettings.dataType.toUpperCase() === 'JSONP' ) {
1362
- if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {
1363
- // This mock will handle the JSONP request
1364
- return mockRequest;
1365
- }
1366
- }
1367
-
1368
-
1369
- // Removed to fix #54 - keep the mocking data object intact
1370
- //mockHandler.data = requestSettings.data;
1371
-
1372
- mockHandler.cache = requestSettings.cache;
1373
- mockHandler.timeout = requestSettings.timeout;
1374
- mockHandler.global = requestSettings.global;
1375
-
1376
- // In the case of a timeout, we just need to ensure
1377
- // an actual jQuery timeout (That is, our reponse won't)
1378
- // return faster than the timeout setting.
1379
- if ( mockHandler.isTimeout ) {
1380
- if ( mockHandler.responseTime > 1 ) {
1381
- origSettings.timeout = mockHandler.responseTime - 1;
1382
- } else {
1383
- mockHandler.responseTime = 2;
1384
- origSettings.timeout = 1;
1385
- }
1386
- mockHandler.isTimeout = false;
1387
- }
1388
-
1389
- // Set up onAfter[X] callback functions
1390
- if ( $.isFunction( mockHandler.onAfterSuccess ) ) {
1391
- origSettings.success = overrideCallback('Success', mockHandler);
1392
- }
1393
- if ( $.isFunction( mockHandler.onAfterError ) ) {
1394
- origSettings.error = overrideCallback('Error', mockHandler);
1395
- }
1396
- if ( $.isFunction( mockHandler.onAfterComplete ) ) {
1397
- origSettings.complete = overrideCallback('Complete', mockHandler);
1398
- }
1399
-
1400
- copyUrlParameters(mockHandler, origSettings);
1401
-
1402
- (function(mockHandler, requestSettings, origSettings, origHandler) {
1403
-
1404
- mockRequest = _ajax.call($, $.extend(true, {}, origSettings, {
1405
- // Mock the XHR object
1406
- xhr: function() { return xhr( mockHandler, requestSettings, origSettings, origHandler ); }
1407
- }));
1408
- })(mockHandler, requestSettings, origSettings, mockHandlers[k]);
1409
-
1410
- return mockRequest;
1411
- }
1412
-
1413
- // We don't have a mock request
1414
- unmockedAjaxCalls.push(origSettings);
1415
- if($.mockjaxSettings.throwUnmocked === true) {
1416
- throw new Error('AJAX not mocked: ' + origSettings.url);
1417
- }
1418
- else { // trigger a normal request
1419
- return _ajax.apply($, [origSettings]);
1420
- }
1421
- }
1422
-
1423
- /**
1424
- * Copies URL parameter values if they were captured by a regular expression
1425
- * @param {Object} mockHandler
1426
- * @param {Object} origSettings
1427
- */
1428
- function copyUrlParameters(mockHandler, origSettings) {
1429
- //parameters aren't captured if the URL isn't a RegExp
1430
- if (!(mockHandler.url instanceof RegExp)) {
1431
- return;
1432
- }
1433
- //if no URL params were defined on the handler, don't attempt a capture
1434
- if (!mockHandler.hasOwnProperty('urlParams')) {
1435
- return;
1436
- }
1437
- var captures = mockHandler.url.exec(origSettings.url);
1438
- //the whole RegExp match is always the first value in the capture results
1439
- if (captures.length === 1) {
1440
- return;
1441
- }
1442
- captures.shift();
1443
- //use handler params as keys and capture resuts as values
1444
- var i = 0,
1445
- capturesLength = captures.length,
1446
- paramsLength = mockHandler.urlParams.length,
1447
- //in case the number of params specified is less than actual captures
1448
- maxIterations = Math.min(capturesLength, paramsLength),
1449
- paramValues = {};
1450
- for (i; i < maxIterations; i++) {
1451
- var key = mockHandler.urlParams[i];
1452
- paramValues[key] = captures[i];
1453
- }
1454
- origSettings.urlParams = paramValues;
1455
- }
1456
-
1457
-
1458
- // Public
1459
-
1460
- $.extend({
1461
- ajax: handleAjax
1462
- });
1463
-
1464
- $.mockjaxSettings = {
1465
- //url: null,
1466
- //type: 'GET',
1467
- log: function( mockHandler, requestSettings ) {
1468
- if ( mockHandler.logging === false ||
1469
- ( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {
1470
- return;
1471
- }
1472
- if ( window.console && console.log ) {
1473
- var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
1474
- var request = $.extend({}, requestSettings);
1475
-
1476
- if (typeof console.log === 'function') {
1477
- console.log(message, request);
1478
- } else {
1479
- try {
1480
- console.log( message + ' ' + JSON.stringify(request) );
1481
- } catch (e) {
1482
- console.log(message);
1483
- }
1484
- }
1485
- }
1486
- },
1487
- logging: true,
1488
- status: 200,
1489
- statusText: "OK",
1490
- responseTime: 500,
1491
- isTimeout: false,
1492
- throwUnmocked: false,
1493
- contentType: 'text/plain',
1494
- response: '',
1495
- responseText: '',
1496
- responseXML: '',
1497
- proxy: '',
1498
- proxyType: 'GET',
1499
-
1500
- lastModified: null,
1501
- etag: '',
1502
- headers: {
1503
- etag: 'IJF@H#@923uf8023hFO@I#H#',
1504
- 'content-type' : 'text/plain'
1505
- }
1506
- };
866
+ // Register as an anonymous AMD module
867
+ if (typeof define === 'function' && define.amd) {
868
+ define('factory-guy', [], function () {
869
+ return FactoryGuy;
870
+ });
871
+ }
1507
872
 
1508
- $.mockjax = function(settings) {
1509
- var i = mockHandlers.length;
1510
- mockHandlers[i] = settings;
1511
- return i;
1512
- };
1513
- $.mockjax.clear = function(i) {
1514
- if ( arguments.length == 1 ) {
1515
- mockHandlers[i] = null;
1516
- } else {
1517
- mockHandlers = [];
1518
- }
1519
- mockedAjaxCalls = [];
1520
- unmockedAjaxCalls = [];
1521
- };
1522
- // support older, deprecated version
1523
- $.mockjaxClear = function(i) {
1524
- window.console && window.console.warn && window.console.warn( 'DEPRECATED: The $.mockjaxClear() method has been deprecated in 1.6.0. Please use $.mockjax.clear() as the older function will be removed soon!' );
1525
- $.mockjax.clear();
1526
- };
1527
- $.mockjax.handler = function(i) {
1528
- if ( arguments.length == 1 ) {
1529
- return mockHandlers[i];
1530
- }
1531
- };
1532
- $.mockjax.mockedAjaxCalls = function() {
1533
- return mockedAjaxCalls;
1534
- };
1535
- $.mockjax.unfiredHandlers = function() {
1536
- var results = [];
1537
- for (var i=0, len=mockHandlers.length; i<len; i++) {
1538
- var handler = mockHandlers[i];
1539
- if (handler !== null && !handler.fired) {
1540
- results.push(handler);
1541
- }
1542
- }
1543
- return results;
1544
- };
1545
- $.mockjax.unmockedAjaxCalls = function() {
1546
- return unmockedAjaxCalls;
1547
- };
1548
- })(jQuery);
873
+ // If there is a window object, that at least has a document property,
874
+ // instantiate and define chance on the window
875
+ if (typeof window === "object" && typeof window.document === "object") {
876
+ window.FactoryGuy = FactoryGuy;
877
+ }
878
+ })();