Function creates instances of controllers, adds into bottle routes
433424
def register_routes(self):
        
        routes = self.flatten_urls(self.urls)
        self.controllers = {}
        controller_names = set()

        for route in routes:
            cname = route['endpoint'].split('.')[0]
            controller_names.add(cname)

        for cname in controller_names:
            attr = getattr(self.mcontrollers, cname)
            instance = attr(request, response)
            self.controllers[cname] = instance

        for route in routes:
            cname, aname = route['endpoint'].split('.')
            action = getattr(self.controllers[cname], aname)
            self.wsgi.route(route['url'], route['methods'], action)
226165
function addControllerRoutes(router) {
  // load all controller routers
  _.each(reservedRoutes, routeName => {
    let pathRouter,
      filename = routeName + '.js',
      controller = files.tryRequire([__dirname, routesPath, filename].join(path.sep));

    // we're okay with an error occurring here because it means we're missing something important in a route
    pathRouter = express.Router();

    // assume json or text for anything in request bodies
    pathRouter.use(require('body-parser').json({ strict: true, type: 'application/json', limit: '50mb' }));
    pathRouter.use(require('body-parser').text({ type: 'text/*' }));

    controller(pathRouter);

    router.use(`/${routeName}`, pathRouter);
  });
}
596743
function(controller, routeOptions) {
      return function(req, res, next) {
        var requiredParams = routeOptions.requiredParams || [];
        var ignoredParams = routeOptions.ignoredParams || [];

        // Omit disallowed params in body and query
        if (ignoredParams.length) {
          req.body = _.omit(req.body, ignoredParams);
          req.query = _.omit(req.query, ignoredParams);
        }

        // Reject request if required params are missing
        if (requiredParams.length) {
          // Find all missing parameters
          // If there are missing parameters,
          // respond with an error before routing
          var missingParams = router._buildMissingParams(req, requiredParams);
          if (missingParams.length) {
            return next(router._buildMissingParamsError(missingParams));
          }
        }

        // Execute the route for the request
        return routeOptions.action.call(controller, req, res, next);
      };
    }
1172546
function logRoute(routeConfig, filters) {
        filters = filters ? filters.join(', ') : "";
        $log.info(
            '{method="%s", path="%s", filters="%s"} bind on controller %s#%s',
            routeConfig.method,
            routeConfig.path,
            filters,
            routeConfig.controller,
            routeConfig.action
        );
    }
291436
function buildForms (args, controller, forms, instance) {
    // promises to be resolved once all forms built
    var promises = []
    // build forms from controller spec
    _.each(forms, form => {
        if (form.type === 'link') {
            var promise = buildFormLink(args, controller, form, instance)
        }
        // add promise to list
        promises.push(promise)
    })
    // wait for promises to resolve then resolve with forms
    return Promise.all(promises)
}
1339378
function generateController(path, modelName, modelFields, generateMethod, ts, cb) {
    var extension = (ts) ? 'ts' : 'js';
    var controller = ft.loadTemplateSync('controller.' + extension);

    var updateFields = '';
    var createFields = os.EOL;

    modelFields.forEach(function (f, index, fields) {
        var field = f.name;

        updateFields += modelName + '.' + field + ' = req.body.' + field + ' ? req.body.' + field + ' : ' +
            modelName + '.' + field + ';';
        updateFields += os.EOL + '\t\t\t';

        createFields += '\t\t\t' + field + ' : req.body.' + field;
        createFields += ((fields.length - 1) > index) ? ',' + os.EOL : '';
    });

    controller = controller.replace(/{modelName}/g, formatTools.capitalizeFirstLetter(modelName) + 'Model');
    controller = controller.replace(/{name}/g, modelName);
    controller = controller.replace(/{pluralName}/g, formatTools.pluralize(modelName));
    controller = controller.replace(/{controllerName}/g, modelName + 'Controller');
    controller = controller.replace(/{createFields}/g, createFields);
    controller = controller.replace(/{updateFields}/g, updateFields);

    if (generateMethod === 't') {
        ft.createDirIfIsNotDefined(path, 'controllers', function () {
            controller = controller.replace(/{modelPath}/g, '\'../models/' + modelName + 'Model.' + extension + '\'');
            ft.writeFile(path + '/controllers/' + modelName + 'Controller.' + extension, controller, null, cb);
        });
    } else {
        ft.createDirIfIsNotDefined(path, modelName, function () {
            controller = controller.replace(/{modelPath}/g, '\'./' + modelName + 'Model.' + extension + '\'');
            ft.writeFile(path + '/' + modelName + '/' + modelName + 'Controller.' + extension, controller, null, cb);
        });
    }
}
249011
function generateGenericControllers(controllers, models) {
        var genericControllers = {},
            genericRoute = [];

        models.forEach(function(model) {
            var persistence = $database.getPersistenceOfModel(model);
            if (null == persistence) {
                throw new Error('');
            }
            var defaultController = {};
            var modelRest = model + "Rest";

            if (controllers.hasOwnProperty(modelRest)) {
                defaultController = controllers[modelRest];
            } else if (controllers.hasOwnProperty(utils.camelizePath(modelRest))) {
                defaultController = controllers[utils.camelizePath(modelRest)];
            }

            var generatorController = persistence.generatorController;

            genericControllers[modelRest] = _.defaults({}, defaultController, generatorController.generate(persistence.repositories[model], true));
            //create
            genericRoute.push({
                method: 'post',
                controller: modelRest,
                action: 'create',
                path: '/' + model
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'createQuery',
                path: '/' + model + '/create'
            });

            //Read
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'index',
                path: '/' + model
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'findById',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'find',
                path: '/' + model + '/find'
            });

            //update
            genericRoute.push({
                method: 'put',
                controller: modelRest,
                action: 'update',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'updateQuery',
                path: '/' + model + '/update/:id'
            });

            //update
            genericRoute.push({
                method: 'delete',
                controller: modelRest,
                action: 'delete',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'delete',
                path: '/' + model + '/delete/:id'
            });

        });

        return [genericControllers, genericRoute]
    }
1332666
function initAppDir (config, module, appDir, appSubDir) {
    // if called without sub dir then start with app dir
    if (!appSubDir) {
        appSubDir = appDir
    }
    // debug
    debug('initAppDir %s', appSubDir)
    // get relative path from app base to directory which determines
    // where in the routes tree this directory sits
    var rel = path.relative(appDir, appSubDir)
    // get route node from relative path
    var route = routeFromRel(module.routes, rel)
    // prevent infinite loops
    if (route.loaded) {
        return
    }
    // mark route as loaded
    route.loaded = true
    // directory names map
    var dirNames = {}
    // list of all sub-directories in directory
    var dirs = []
    // list of all files in directory
    var files = []
    // iterate over file names in directory
    _.each(fs.readdirSync(appSubDir), file => {
        // get absolute file
        var absFile = appSubDir+'/'+file
        // get stat of file to check if it is dir or file
        var stat = fs.statSync(absFile)
        // file
        if (stat.isFile()) {
            files.push(absFile)
        }
        // directory
        else if (stat.isDirectory()) {
            // add name to map for doing conflict checking
            dirNames[file] = true
            // add abs path to list for recursive loading
            dirs.push(absFile)
        }
        // ignore anything else
        else {
            debug('initAppDir: ignoring %s', absFile)
        }
    })
    // recursively process all sub-directories - go depth first so that routes
    // for sub-dirs are added before wildcard path param matching rules
    _.each(dirs, dir => {
        initAppDir(config, module, appDir, dir)
    })
    // regular expression for matching controller files
    var controllerRegEx = /controller\.js$/
    // regular expression for matching model files
    var modelRegEx = /model\.js$/
    // regular expression for matching template files extname starts with .
    config.handlebars.templateRegExp = new RegExp('\\'+config.handlebars.ext+'$')
    // ImmutableCoreController for node - multiple files will be merged
    route.controller = {}
    // ImmutableCoreModel for node - multiple files will be merged
    route.model = {}
    // list of templates indexed by name. name of template file indicates path
    // that it should be served on. if path does not have a controller then
    // a default controller will be created.
    route.templates = {}
    // get mapping of templates by path
    route.templatesInverse = {}
    // require all controller and model files for route
    _.each(files, file => {
        // get type
        var type
        // controllers must be named controller.js
        if (file.match(controllerRegEx)) {
            // require controller file
            var controller = require(path.relative(__dirname, file))
            // require defined
            assert.ok(defined(controller), `nothing exported for ${file}`)
            // throw error if controller instantiated
            assert.ok(!controller.ImmutableCoreController, `controller must be plain object ${file}`)
            // merge controller spec
            _.merge(route.controller, controller)
        }
        // models must be named model.js
        else if (file.match(modelRegEx)) {
            // require model file
            var model = require(path.relative(__dirname, file))
            // require defined
            assert.ok(defined(model), `nothing exported for ${file}`)
            // throw error if controller instantiated
            assert.ok(!model.ImmutableCoreModel, `model must be plain object ${file}`)
            // merge model spec
            _.merge(route.model, model)
        }
        // template files must end in hbs
        else if (file.match(config.handlebars.templateRegExp)) {
            // get only the file name
            file = path.basename(file)
            // remove extension from file
            file = file.replace(config.handlebars.templateRegExp, '')
            // template path used in render call is relative path from app
            // base (if any) and the file name without the extensions
            var templatePath = (rel.length ? rel+'/' : '') + file
            // split file name on dot - if template name has a dot then the
            // part after the dot must be the role that the template is for
            var fileParts = file.split('.')
            // if there is only a single part then not a role specific template
            if (fileParts.length === 1) {
                // if entry does not exist for template name then create it
                if (!defined(route.templates[file])) {
                    route.templates[file] = {
                        role: {},
                    }
                }
                // store template name and template path under default all role
                route.templates[file].role.all = templatePath
                // create inverse entry keyed by full path
                route.templatesInverse[templatePath] = {
                    name: file,
                    role: 'all',
                }
            }
            // it there are two parts they must be name.role
            else if (fileParts.length === 2) {
                var name = fileParts[0]
                var role = fileParts[1]
                // if entry does not exist for template name then create it
                if (!defined(route.templates[name])) {
                    route.templates[name] = {
                        role: {},
                    }
                }
                // store template name and template path
                route.templates[name].role[role] = templatePath
                // create inverse entry keyed by full path
                route.templatesInverse[templatePath] = {
                    name: name,
                    role: role,
                }
            }
            // if there are not 1 or 2 parts this is an error
            else {
                throw new Error('invalid template file name '+file)
            }
        }
        // otherwise ignore file
        else {
            return
        }
    })
    // if controller name is not set construct from module name
    if (!defined(route.controller.name)) {
        // get controller name as app + path
        route.controller.name = changeCase.camelCase(module.name)
            + changeCase.pascalCase(rel.length ? rel : 'Index')
    }
    // if controller path is not set use current relative path
    if (!defined(route.controller.path)) {
        route.controller.path = rel
    }
}
924506
function createRouter(ClonedVue, routes = []) {
    let VueRouter = require('vue-router');

    if (typeof VueRouter.default === 'function') {
        VueRouter = VueRouter.default;
    }

    ClonedVue.use (VueRouter);

    const normalizedRoutes = routes.map(route => {
        return typeof route === 'string'
            ? stubRoute(route)
            : route;
    });

    return new VueRouter({
        mode: 'abstract',
        routes: normalizedRoutes,
    });
}
438904
def add_route_for_all_verbs(path, controller)
      add_route('GET', path, controller)
      add_route('POST', path, controller)
      add_route('DELETE', path, controller)
      add_route('PUT', path, controller)
    end
205029
function Routes(opts, items) {
	var self = this;
	opts = opts || {};
	items = items || [];
	debug.assert(self).is('object');
	debug.assert(opts).is('object');
	debug.assert(items).is('array');

	opts = copy(opts);
	self.file = opts.file;
	self.items = copy(items);
	self.changed = opts.changed || false;

	debug.assert(self.items).is('array');

	// Make an object (hash map) as an index for searching targets faster (path + method)
	self.targets = {};
	load_targets(self);

	debug.assert(self.file).is('string');
	debug.assert(self.targets).is('object');
}
1322634
function controllerLinks(route, controllerAction, reverseRouteService) {
  const controllers = sails.controllers;
  const controller = _.first(controllerAction.split('.'));
  const path = route.path;
  const actions = _.get(controllers[controller], '_config.links') || [];
  let result = {};
  result[path] = [];
  _.each(actions, function (action) {
    return result[path].push({
      rel: action,
      link: reverseRouteService({controller: controller + '.' + action, args: []}, false)
    });
  });
  return result;
}
446736
protected function makeControllerInstance()
    {
        list($this->controllerClass, $this->controllerMethod) = explode('@', $this->action['uses']);

        $this->container->instance($this->controllerClass,
            $this->controller = $this->container->make($this->controllerClass));

        return $this->controller;
    }
117915
function __bindController (newController, sessionExpiration) {
    if (controller && typeof(controller.shutdown) === 'function') {
        controller.shutdown();
    }
    controller = newController;
    if (typeof(controller.clientInit) === 'function') {
        controller.clientInit(sessionExpiration);
    }
}
546478
function (scope, cb) {

    // scope.args are the raw command line arguments.
    //
    // e.g. if someone runs:
    // $ sails generate controller-ts user find create update
    // then `scope.args` would be `['user', 'find', 'create', 'update']`
    if (!scope.args[0]) {
      return cb( 'Usage: sails generate controller-ts <controllername>' );
    }

    if (!scope.rootPath) {
      return cb( INVALID_SCOPE_VARIABLE('rootPath') );
    }

    // Ensure that the command is ran from root.
    if (!isValidRoot(scope.rootPath)) {
      return cb( INVALID_ROOT_PATH() );
    }

    // Ensure that the name is valid
    if (!isValidName(scope.args[0])) {
      return cb( INVALID_NAME() );
    }

    checkMissingDefinitions(scope.rootPath);
    
    // Attach defaults
    _.defaults(scope, {
      createdAt: new Date()
    });

    // Limit controller name correctly.
    var capitalizedName = capitalize(scope.args[0]);
    scope.controllerName = capitalizedName + 'Controller';
    // Pluralize item.
    scope.modelName = pluralize(capitalizedName);

    if (doesControllerExist(scope.rootPath, scope.controllerName)) {
      return cb( ALREADY_EXISTS(scope.controllerName) );
    }

    // Decide the output filename for use in targets below:
    scope.filename = '/api/controllers/' + scope.controllerName + '.ts';

    cb();
  }
358085
function initModelNew (args) {
    var controller = this
    var model = this.model
    // if model/controller does not have form then cannot create new controller
    if (!this.form) {
        return
    }
    // create path if it does not exist
    if (!this.paths['/new']) {
        this.paths['/new'] = {}
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // form inputs
    var input = {
        redirect: 'query.redirect',
    }
    // input may include pre-filled form values
    input[model.name] = 'query.'+model.name
    // add handler for GET /new
    this.paths['/new'].get = [
        {
            before: function (args) {
                return newInstance(controller, args)
            },
            input: input,
            method: function (args) {
                return {form: args.form}
            },
            methodName: 'new',
            role: role,
            template: 'instance',
        },
    ]
}
1314139
def app_controllers_recursive(path)
      invalid_entries = ['..', '.', 'concerns']

      (Dir.entries(path) - invalid_entries).each do |entry|
        if File.directory?(path + entry)
          app_controllers_recursive(path + entry + '/')
        elsif File.extname(entry) == '.rb'
          parent_directory = File.dirname(path + entry).split(/\//).last

          container = if parent_directory == 'controllers'
            'default'
          else
            parent_directory
          end

          @controllers[container.to_sym] ||= []

          unless File.basename(path + entry, '.*') == 'application_controller'
            @controllers[container.to_sym] << File.basename(path + entry, '.*')
          end
        end
      end
      @controllers
    end