Sets middleware on the referenced models

@param {object} Model - The current model, where this plugin is running
@param {string} modelName - the model that is being referenced
@param {string} path - the property with the reference
426279
function setMiddleware(Model, modelName, path) {
        var RefModel;

        // We only apply the middleware on the provided 
        // paths in the plugin options.
        if (opts.onDeleteRestrict.indexOf(path) === -1) {
            return;
        }

        RefModel = models[modelName];
        RefModel.schema.pre('remove', function (next) {
            var doc = this,
                q = {};

            q[path] = doc._id;

            Model
                .findOne(q)
                .exec()
                .then(function (doc) {
                    if (doc) {
                        return next(new Error('Unable to delete as ref exist in ' + Model.modelName + ' id:' + doc._id));
                    }
                    next();
                }, next);
        });
    }
457373
function loadModels() {
  if(this.config.path.models == false) return;
  var MODEL_LOCATION = Component.appPath(this.config.path.models),
    self = this;
  try {
    var list = Crux.util.readDirectory(MODEL_LOCATION, 'js');
  } catch(e) {
    // Component has no models.
    return;
  }
  list.forEach(function(modelPath) {
    var fileName = Crux.util.getFileName(modelPath);
    var tableName = fileName.replace('.js', '');
    tableName = tableName.replace(/\//g, '_').replace(/\\/g, '_');
    var modelName = Crux.util.capitalize(tableName, true);
    var modelObj = self.Register(modelName, tableName);
    var modelFunc = require(modelPath);
    if(typeof modelFunc !== 'function') {
      log.warn('Crux.sql: failed to load model definition "%s", not a function', modelName);
      return;
    }
    modelFunc(modelObj, Sequelize, self);
    if(!modelObj.hasFields) {
      log.warn('Crux.sql: Model definition "%s" has no fields. Skipping', modelName);
      return;
    }
    var _opt = modelObj.options;
    if(modelObj.hasValidations) {
      _opt['validate'] = {};
      _.forEach(modelObj.validations, function(callback, name) {
        _opt['validate'][name] = callback;
      });
    }
    if(modelObj.hasMethods) {
      _opt['instanceMethods'] = {};
      _.forEach(modelObj.methods, function(callback, name) {
        _opt['instanceMethods'][name] = callback;
      });
    }
    if(modelObj.hasStatics) {
      _opt['classMethods'] = {};
      _.forEach(modelObj.statics, function(callback, name) {
        if(typeof callback === 'function') {
          _opt['classMethods'][name] = callback;
        }
      });
    }
    if(modelObj.hasJsonFields) {
      modelObj.markJsonFields();
    }
    _opt['syncOnAssociation'] = false;
    try {
      MODELS[modelObj.__name] = self.Seq.define(modelObj.__name, modelObj.fields, _opt);
    } catch(e) {
      log.error('crux.sql: Failed to load SQL model definition: %s', modelObj.__name);
      throw e;
    }
    modelObj.bindMethods(MODELS[modelObj.__name]);
    modelObj.bind(MODELS[modelObj.__name]);
    if(modelObj.hasRelationships) {
      RELATIONSHIPS.push(modelObj);
    }
    if(modelObj.hasStatics) {
      _.forEach(modelObj.statics, function(data, fieldName) {
        if(typeof data !== 'function') {
          MODELS[modelObj.__name][fieldName] = data;
        }
      });
    }
  });
  RELATIONSHIPS.forEach(function(modelObj) {
    var sourceModel = MODELS[modelObj.__name];
    /* Has many */
    _.forEach(modelObj.__hasMany, function(depOpt, depName) {
      var targetModel = MODELS[depName];
      if(typeof depOpt['through'] === 'string') {
        depOpt['through'] = MODELS[depOpt['through']];
      }
      try {
        sourceModel.hasMany(targetModel, depOpt);
      } catch(e) {
        log.fatal('Failed to do hasMany on %s-%s',depName, modelObj.__name);
        log.debug(e);
      }
    });
    /* Has one */
    _.forEach(modelObj.__hasOne, function(depOpt, depName) {
      var targetModel = MODELS[depName];
      try {
        sourceModel.hasOne(targetModel, depOpt);
      } catch(e) {
        log.fatal('Failed to do hasOne on %s-%s', depName, modelObj.__name);
        log.debug(e);
      }
    });
    /* Belongs to */
    _.forEach(modelObj.__belongsTo, function(depOpt, depName) {
      var targetModel = MODELS[depName];
      try {
        sourceModel.belongsTo(targetModel, depOpt);
      } catch(e) {
        log.fatal('Failed to do belongsTo on %s-%s', depName, modelObj.__name);
        log.debug(e);
      }
    });
  });
  /*
   * We now bind the mock() function for all our loaded models.
   * */
  _.forEach(MODELS, function(modelObj, name) {
    /*
     * The mock function will be attached on all our models and will return a object model with generated data.
     * */
    modelObj.mock = function MockJsonModel(data) {
      if(typeof data !== 'object' || data === null) data = {};
      var mockData = {};
      // We bind the raw attributes
      for(var attr in modelObj.rawAttributes) {
        if(typeof data[attr] !== 'undefined') {
          mockData[attr] = data[attr];
          continue;
        }
        // If by any change, we have set some default values, we take one of them.
        if(modelObj.rawAttributes[attr].type.values instanceof Array) {
          var idx = Math.floor(Math.random() * modelObj.rawAttributes[attr].type.values.length);
          mockData[attr] = modelObj.rawAttributes[attr].type.values[idx];
          continue;
        }
        // We now generate a random value.
        var rawAttr = modelObj.rawAttributes[attr],
          aName = _.isString(rawAttr.type.type) ? rawAttr.type.type :
            (_.isString(rawAttr.type._typeName) ? rawAttr.type._typeName : rawAttr.type);
        /* If by any chance we have a rawAttribute that is used in foreign keys, we skip it */
        if(typeof rawAttr['references'] !== 'undefined') {
          continue;
        }
        if(aName.indexOf("VARCHAR") !== -1 && (typeof rawAttr.type._parseJson === 'undefined')) {
          mockData[attr] = Crux.util.uniqueId(5);
        }
        if(aName.indexOf("INTEGER") !== -1) {
          mockData[attr] = Math.floor(Math.random() * 100);
        }
        if(aName.indexOf("FLOAT") !== -1) {
          mockData[attr] = parseFloat(Math.random().toFixed(3));
        }
        if(aName.indexOf("DATE") !== -1) {
          mockData[attr] = new Date();
        }
        if(aName.indexOf("BOOLEAN") !== -1) {
          var now = new Date().getTime();
          mockData[attr] = (now % 2 === 0 ? true : false);
        }
      }
      var buildedMockObj = modelObj.build(mockData);
      // We now go through the model's associations.
      // We only create the association if the user explicitly states it
      for(var assocName in modelObj.associations) {
        var assocObj = modelObj.associations[assocName];
        if(typeof data[assocName] === 'undefined') continue;
        if(assocObj.associationType === 'HasMany' && data[assocName] instanceof Array) {
          //buildedMockObj.setDataValue(assocObj.associationAccessor, []);
          var _mocks = [];
          for(var i=0; i < data[assocName].length; i++) {
            var targetMock = assocObj.target.mock(data[assocName][i]);
            _mocks.push(targetMock);
          }
          if(_mocks.length !== 0) {
            buildedMockObj.setDataValue(assocName, _mocks);
          }
          continue;
        }
        if((assocObj.associationType === 'BelongsTo' || assocObj.associationType === 'HasOne') && typeof data[assocName] === 'object') {
          var targetMock = assocObj.target.mock(data[assocName]).toJSON();
          buildedMockObj.setDataValue(assocName, targetMock);
          continue;
        }
      }
      return buildedMockObj;
    };
  });
}
1256111
function (model, options, callback) {
                var schema = model.schema,
                    subModels = [],
                    type,
                    subCollection,
                    subModel,
                    addSubModel = function (model) {
                        subModels.push(model);
                    };

                for (var reference in schema) {
                    if (schema.hasOwnProperty(reference)) {
                        type = schema[reference];
                        if (type.classof) {
                            // TODO: remove $nestedModels and use options to specify, which subModels should also be saved
                            // This depends on the changes of the model.
                            // If the submodels haven't changed, than there is no need to save sub models/collections.
                            if (type.classof(Model)) {
                                subModel = model.$[reference];
                                if (subModel && _.include(model.$nestedModels, reference)) {
                                    subModels.push(subModel);
                                }
                            } else if (type.classof(Collection)) {
                                subCollection = model.$[reference];
                                if (subCollection) {
                                    subCollection.each(addSubModel);
                                }
                            }
                        }

                    }
                }

                flow()
                    .parEach(subModels, function (model, cb) {
                        model.save(options, cb);
                    })
                    .exec(callback);
            }
818995
function(req) {

    // Ensure a model can be deduced from the request options.
    var model = req.options.model || req.options.controller;
    if (!model) {
      throw new Error('No "model" specified in route options.');
    }

    var Model = req._sails.models[model];
    if (!Model) {
      throw new Error('Invalid route option, "model". No model named: ' + model);
    }

    return Model;
  }
1253407
function _ensureModel(model) {
      if (model instanceof this.model) {
        return model;
      } else if (typeof model === "object") {
        return new this.model(model);
      } else {
        return new this.model({ id: model });
      }
    }
536125
function Model(attributes, options) {
  var _attributes = attributes || {};
  options = options || {};
  this.attributes = Object.create(null);
  this.set(_attributes, options);
  this.initialize.apply(this, arguments);
}
779150
def setModel(self, model):
        

        LOGGER.debug("> Setting '{0}' model.".format(model))

        if not model:
            return

        umbra.ui.views.Abstract_QTreeView.setModel(self, model)
1146115
function loadModels(fpath, modelFiles) {
    try {
      fpath = path.normalize(fpath);
      if (!fs.existsSync(fpath)) throw 1;
    } catch (e) {
      return false;
    }
    if (path.extname(fpath) === '.js') {
      // we have a file.
      let itemName = path.basename(fpath);
      itemName = itemName.substr(0, itemName.lastIndexOf('.'));
      let itemCode = decamelize(itemName);
      let item = {
        fullPath: fpath,
        code: itemCode,
        name: itemName,
        path: path.basename(fpath)
      };
      modelFiles.push(item);
      return true;
    }
    const items = thorin.util.readDirectory(fpath, {
      ext: 'js',
      relative: true
    });
    if (items.length === 0) {
      return true;
    }
    for (let i = 0; i < items.length; i++) {
      let itemPath = items[i];
      let item = {
        fullPath: path.normalize(fpath + '/' + itemPath)
      };
      itemPath = itemPath.substr(0, itemPath.lastIndexOf('.'));
      let itemName = decamelize(itemPath, NAME_SEPARATOR);
      itemName = itemName.split(path.sep).join(NAME_SEPARATOR);
      item.name = itemName;
      item.code = camelcase(itemName);
      item.path = itemPath.split(path.sep).join('/');
      modelFiles.push(item);
    }
    return true;
  }
84888
function initModel (args) {
    // if model is not passed then do nothing
    if (!args.model) {
        return
    }
    // if paths is false then do not create any default paths
    if (args.paths === false) {
        return
    }
    // require object to have ImmutableCoreObject class property
    assert.ok(args.model.ImmutableCoreModel, 'invalid model')
    // save model
    this.model = args.model
    // register controller with model
    this.model.controller = this
    // if model has data then create form for it
    if (this.model.schemaData && _.keys(this.model.schemaData.properties).length) {
        // build args for new form
        var formArgs = {
            action: './',
            method: 'POST',
            model: this.model,
            submit: {
                title: 'Create '+changeCase.titleCase(this.model.name),
            },
            title: 'New '+changeCase.titleCase(this.model.name),
        }
        // merge any args for form
        _.merge(formArgs, args.form)
        // create new form instance from model
        this.form = new ImmutableCoreModelForm(formArgs)
    }
    // create path entry if it does not exist
    if (!this.paths) {
        this.paths = {}
    }
    // create actions object
    this.actions = {}
    // merge actions from controller spec
    if (defined(args.actions)) {
        // do not allow array
        if (Array.isArray(args.actions)) {
            throw new Error(`actions array deprecated for controller ${this.model.name}`)
        }
        // get actions from controller spec
        _.merge(this.actions, args.actions)
    }
    // create list view controller
    this.initModelList(args)
    // new instance controller
    this.initModelNew(args)
    // create instance controller
    this.initModelCreate(args)
    // get instance controller
    this.initModelRead(args)
    // update instance controller
    this.initModelUpdate(args)
    // link model to relations controller
    this.initModelLink(args)
    // unlink model from relation controller
    this.initModelUnlink(args)
    // delete instance controller
    this.initModelDelete(args)
    // model schema controller
    this.initModelSchema(args)
    // validate data controller
    this.initModelValidate(args)
}
876209
def set_model_pathnames(self):
        """"""
        self.control_path = self.expt.control_path
        self.input_basepath = self.expt.lab.input_basepath
        self.work_path = self.expt.work_path
        self.codebase_path = self.expt.lab.codebase_path

        if len(self.expt.models) > 1:

            self.control_path = os.path.join(self.control_path, self.name)
            self.work_path = os.path.join(self.work_path, self.name)
            self.codebase_path = os.path.join(self.codebase_path, self.name)

        # NOTE: Individual models may override the work subdirectories
        self.work_input_path = self.work_path
        self.work_restart_path = self.work_path
        self.work_output_path = self.work_path
        self.work_init_path = self.work_path

        self.exec_prefix = self.config.get('exe_prefix', '')
        self.exec_name = self.config.get('exe', self.default_exec)
        if self.exec_name:
            # By default os.path.join will not prepend the lab bin_path
            # to an absolute path
            self.exec_path = os.path.join(self.expt.lab.bin_path,
                                          self.exec_name)
        else:
            self.exec_path = None

        if self.exec_path:
            # Make exec_name consistent for models with fully qualified path.
            # In all cases it will just be the name of the executable without a
            # path
            self.exec_name = os.path.basename(self.exec_path)
1092959
function Model(name, config) {
	this.name = name;

	utils.defaultsDeep(config, {
		attributes: {},
		sharedMethods: {},
		clientMethods: {},
		serverMethods: {},
		hooks: {},
		options: {
			allowREST: true,
			middlewares: [],
			generateClientModel: true,
			hooks: {}
		},
		relationships: {}
	});

	//Copy all configs to the model object
	for(var c in config) {
		if(config.hasOwnProperty(c)) {
			this[c] = config[c];
		}
	}

	return this;
}
609838
function (routerMiddelware, req, res, next) {
		var middlewareFilename = routerMiddelware.split('.')[0];
		var middlewareFunction = routerMiddelware.split('.')[1];

		if (!req.pipa) req.pipa = {};

		this.middlewares[middlewareFilename][middlewareFunction](req, res, function (data) {
			_.extend(req.pipa, data); next();
		});
	}
446940
function bindMiddlewares() {
		var modelName,
			_this = this;

		for(modelName in Rhapsody.models) {

			(function(model) {

				model.options.middlewares.forEach(function(middleware) {
					if(typeof middleware !== 'function') {
						middleware = require(path.join(Rhapsody.root, '/app/middlewares/' + middleware));
					}

					modelName = '/' + modelName;

					_this.router.post(modelName, middleware);
					_this.router.post(modelName + '/:id/:relationship', middleware);
					_this.router.get(modelName + '/:id?', middleware);
					_this.router.get(modelName + '/:id/:relationship', middleware);
					_this.router.put(modelName + '/:id', middleware);
					_this.router.patch(modelName + '/:id', middleware);
					_this.router.delete(modelName + '/:id', middleware);
				});

			}(Rhapsody.models[modelName]));
		}
	}
595172
function requireModel(filePath, cb) {
        //check if file exist. if not return error
        fs.exists(filePath, function (exists) {
            if (!exists) {
                soajs.log.error('Requested Model Not Found!');
                return cb(601);
            }

            driver.model = require(filePath);
            return cb();
        });
    }
1085295
function (next, model) {
            if (this.isOwner && !this.isCascading) {
                var q = {};
                this._setAssociationKeys(model, q, null);
                model[this.associatedDatasetName].update(q).classic(next);
            } else {
                next();
            }
        }
568148
function defineModel(file) {
    var object      = require(file),
        options     = object.options || {},
        modelName   = object.modelName;

    if (debug) {
        fs.writeSync(debugFD, 'var ' + modelName + ' = Sequelize.define("' + modelName + '",\n' + util.inspect(object.attributes) + ',\n' + util.inspect(options, {depth: null}) + ');\n\n\n');
    }

    models[modelName] = sequelize.define(modelName, object.attributes, options);
    if (object.relations !== undefined) {
        relationships[modelName] = object.relations;
    }
}
14393
public void loadModel(String path) {
        Config cfg = Config.newConfig(path);

        loadSection(this, cfg, "r");
        loadSection(this, cfg, "p");
        loadSection(this, cfg, "e");
        loadSection(this, cfg, "m");

        loadSection(this, cfg, "g");
    }