目录
vue-cli3以下版本中,关于webpack的一些配置都在config目录文件中,可是vue-cli3以上版本中,没有了config目录,那该怎么配置webpack呢?
3.x初始化项目后没有了build和config文件,如果你想对webpack相关内容进行配置,需要自己在根目录下(与package.json同级)创建一个vue.config.js文件,这个文件一旦存在,那么它会被 @vue/cli-service 自动加载。(但需要我们自己手动创建哦vue.config.js,跟package.json同级)
在配置中绝大多数都是(可选项)
常规操作还是用到了commjs语法
module.exports = {
}
部署应用包的基本Url,默认/, 可以设置为相对路径./,这样打出来的包,可以部署到任意路径上
let developmentPath='./';//开发环境-npm run serve时引用文件路径
let productionPath='./';//生产环境-npm run build打包后引用文件路径
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? productionPath: developmentPath, // 基本路径-引用文件的路
}
输出文件目录(打包后生成的目录,默认dist)
module.exports = {
outputDir: __dirname + '/server/dist', //build之后静态文件输出路径
//outputDir: 'dist',
}
打包后生成的静态资源目录,默认“ ” ,也就是我们打包后的css,js等存放的位置
module.exports = {
assetsDir: 'static',
}
是否在保存的时候检查
module.exports = {
lintOnSave: process.env.NODE_ENV !== 'production',// eslint-loader
}
生产环境的 source map,可以将其设置为 false 以加速生产环境构建,默认值是true
module.exports = {
productionSourceMap: false,
}
可通过 devServer.proxy解决前后端跨域问题(反向代理)
module.exports = {
// 反向代理
devServer: {
index: '/login.html', //默认打开文件
open: true, //自动打开浏览器
host: 'localhost', //默认打开域名
port: 8080, //默认打开端口号
https: false, //开启关闭https请求
hotOnly: false, //热更
proxy: {
// 配置跨域
'/api': {
target: 'http://dev.aabb.cn:8082/', //代理地址,这里设置的地址会代替axios中设置的baseURL
ws: true, //// proxy websockets
changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
pathRewrite: { //pathRewrite方法重写url
'^/api': '/',
},
},
},
},
}
扩展: hot 和 hotOnly 的区别是在某些模块不支持热更新的情况下,前者会自动刷新页面,后者不会刷新页面,而是在控制台输出热更新失败
module.exports = {
chainWebpack: (config) => {
config.plugins.delete('preload')
config.plugins.delete('prefetch')
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]',
})
.end()
const imagesRule = config.module.rule('images')
imagesRule.uses.clear() //清除原本的images loader配置
imagesRule
.test(/\.(jpg|gif|png|svg)$/)
.exclude.add(path.join(__dirname, '../node_modules')) //不对node_modules里的图片转base64
.end()
.use('url-loader')
.loader('url-loader')
.options({ name: 'img/[name].[hash:8].[ext]', limit: 6000000 })
config.optimization.splitChunks({
cacheGroups: {
vendors: {
name: 'chunk-vendors',
minChunks: pageNum,
test: /node_modules/,
priority: -10,
chunks: 'initial',
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true,
},
},
})
},
}
扩展:
Preload: 用于标记页面加载后即将用到的资源,浏览器将在主体渲染前加载preload标记文件。Vue CLI 应用会为所有初始化渲染需要的文件自动生成 preload 提示;
Prefetch: 用于标记浏览器在页面加载完成后,利用空闲时间预加载的内容。Vue CLI 应用默认为所有作为 async chunk 生成的 JavaScript 文件 (通过动态 import() 按需 code splitting 的产物) 自动生成prefetch提示。
webpack配置
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']
const Version = 'V6.1'
const Timestamp = new Date().getTime()
module.exports = {
webpack配置
configureWebpack: (config) => {
// 为生产环境修改配置
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_debugger: true,//生产环境自动删除debugger
drop_console: true, //生产环境自动删除console
},
warnings: false,
},
sourceMap: false, //关掉sourcemap 会生成对于调试的完整的.map文件,但同时也会减慢打包速度
parallel: true, //使用多进程并行运行来提高构建速度。默认并发运行数:os.cpus().length - 1。
}),
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8,
})
)
}
// 在这里配置后,减少了压缩的包内容,需要在public/index.html通过cdn方式再引入,注意对应的版本
config.externals = {
vue: 'Vue',
'vue-router': 'VueRouter',
vuex: 'Vuex',
axios: 'axios',
jquery: '$',
moment: 'moment',
'mint-ui': 'MINT'
},
// 别名配置
Object.assign(config, {
// 开发生产共同配置
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@c': path.resolve(__dirname, './src/components'),
'@p': path.resolve(__dirname, './src/pages')
}
}
}),
config.output.filename = `[name].${Version}.${Timestamp}.js` //打包生成的文件
config.output.chunkFilename = `[name].${Version}.${Timestamp}.js`
},
}
扩展:
entry:{
main:__dirname + '/app/main.js',
index:__dirname + '/app/index.js'
},
output:{
path:__dirname + '/public', //通过HtmlWebpackPlugin插件生成的html文件存放在这个目录下面
filename:'/js/[name].js', //编译生成的js文件存放到根目录下面的js目录下面,如果js目录不存在则自动创建
/*
* chunkFilename用来打包require.ensure方法中引入的模块,如果该方法中没有引入任何模块则不会生成任何chunk块文件
* 比如在main.js文件中,require.ensure([],function(require){alert(11);}),这样不会打包块文件
* 只有这样才会打包生成块文件require.ensure([],function(require){alert(11);require('./greeter')})
* 或者这样require.ensure(['./greeter'],function(require){alert(11);})
* chunk的hash值只有在require.ensure中引入的模块发生变化,hash值才会改变
* 注意:对于不是在ensure方法中引入的模块,此属性不会生效,只能用CommonsChunkPlugin插件来提取
* */
chunkFilename:'js/[chunkhash:8].chunk.js'
},
在这里configureWebpack和chainWebpack的作用相同,唯一的区别就是他们修改webpack配置的方式不同:
这里配置了全局sass 需要安装的依赖 sass-loader less-loader
css: {
loaderOptions: {
scss: {
additionalData: `@import "@/assets/css/reset.scss";@import "@/assets/css/globle.scss";` //注意配置的键名
},
postcss: {
plugins: [
//remUnit这个配置项的数值是多少呢??? 通常我们是根据设计图来定这个值,原因很简单,便于开发。
//假如设计图给的宽度是750,我们通常就会把remUnit设置为75,这样我们写样式时,可以直接按照设计图标注的宽高来1:1还原开发。
require('postcss-px2rem')({
remUnit: 37.5
})
]
}
}
},
由于 sass-loader 版本不同,loaderOptions 中的 additionalData 的键名也不同
vue-cli3中的webpack与vue多页面应用开发
相关参数:
module.exports = {
pages:{
main: {
// page 的入口
entry: "src/pages/main/main.js",
// 模板来源
template: "public/index.html",
// 在 dist/index.html 的输出
filename: "main.html",
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: "Index Page",
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ["chunk-vendors", "chunk-common", "main"]
},
hh: {
// page 的入口
entry: "src/pages/login/main.js",
// 模板来源
template: "public/index.html",
// 在 dist/index.html 的输出
filename: "login.html",
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: "Index Page",
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ["chunk-vendors", "chunk-common", "hh"]
},
// 当使用只有入口的字符串格式时,
// 模板会被推导为 `public/subpage.html`
// 并且如果找不到的话,就回退到 `public/index.html`。
// 输出文件名会被推导为 `subpage.html`。
subpage: "src/subpage/main.js"
},
}
封装
const glob = require('glob') // 引入glob模块,用于扫描全部src/pages/**/main.js(返回的是一个数组)
// 打包多入口文件基本配置
function getPagesInfo() {
let pages = {}
glob.sync('src/pages/**/main.js').forEach((entry, i) => {
let name = entry.slice(10, -8)
pages[name] = {
entry: entry,
template: 'public.index.html',
filename: name + '.html',
title: '',
chunks: ["chunk-vendors", "chunk-common", name]
}
})
return pages
}
module.exports = {
pages: getPagesInfo(),
publicPath: './kk',
assetsDir: 'static',
};
当运行项目并且打包的时候,会发现chunk-vendors.js这个文件非常大,那是因为webpack将所有的依赖全都压缩到了这个文件里面,这时我们可以将其拆分,将所有的依赖都打包成单独的js;
/*
利用splitChunks将每个依赖包单独打包,在生产环境下配置,代码如下
*/
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production'
// 将每个依赖包打包成单独的js文件
let optimization = {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 20000, // 依赖包超过20000bit将被单独打包
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name (module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`
}
}
}
}
}
Object.assign(config, {
optimization
})
}
}
上面已经提到过去掉打印的操作(console、debug)这里详细讲解一下
首先下载相关插件 uglifyjs-webpack-plugin
npm i -D uglifyjs-webpack-plugin
在vue.config.js文件中引入,并在configureWebpack的optimization中添加如下代码
const UglifyPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production'
// 将每个依赖包打包成单独的js文件
let optimization = {
/*以下代码适用于uglifyjs-webpack-plugin 2.1.1及以前的版本*/
minimizer: [new UglifyPlugin({
uglifyOptions: {
compress: {
warnings: false,
drop_console: true, // console
drop_debugger: false,
pure_funcs: ['console.log'] // 移除console
}
}
})]
}
Object.assign(config, {
optimization
})
}
}
}
新版uglifyjs-webpack-plugin需写成以下方式
minimizer: [new UglifyPlugin({
uglifyOptions: {
warnings: false,
compress: {
drop_console: false, // console
drop_debugger: false,
pure_funcs: ['console.log'] // 移除console
}
}
})]
gizp压缩是一种http请求优化方式,通过减少文件体积来提高加载速度。html、js、css文件甚至json数据都可以用它压缩,可以减小60%以上的体积。webpack在打包时可以借助 compression webpack plugin 实现gzip压缩。
下载 compression webpack plugin
npm i -D compression-webpack-plugin
vue.config.js配置
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production';
if(openGzip){
config.plugins = [
...config.plugins,
new CompressionPlugin({
test:/\.js$|\.html$|.\css/, //匹配文件名
threshold: 10240,//对超过10k的数据压缩
deleteOriginalAssets: false //不删除源文件
})
]
}
} else {
// 为开发环境修改配置...
config.mode = 'development';
}
}
}
{
"name": "demo-cli3",
"version": "1.0.0",
"openGizp": false,
...
}
下载image-webpack-loader
npm install --save-dev image-webpack-loader
在vue.config.js中修改相关配置
4M的图片使用默认设置压缩成1.4M,自定义的设置可以更小
module.exports = {
...
// 默认设置
const defaultOptions = {
bypassOnDebug: true
}
// 自定义设置
const customOptions = {
mozjpeg: {
progressive: true,
quality: 50
},
optipng: {
enabled: true,
},
pngquant: {
quality: [0.5, 0.65],
speed: 4
},
gifsicle: {
interlaced: false,
},
// 不支持WEBP就不要写这一项
webp: {
quality: 75
}
}
chainWebpack: config => {
config.module.rule('images')
.test(/\.(gif|png|jpe?g|svg)$/i)
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options(customOptions)
.end()
}
}
npm i -S lib-flexible postcss-px2rem
在项目入口中main.js 中引入lib-flexible
import 'lib-flexible'
# 注意事项: 由于flexible会动态给页面header中添加<meta name='viewport' >标签,所以务必请把目录 public/index.html 中的这个标签删除!!
项目中vue.config.js中进行如下的配置
module.exports = {
css: {
loaderOptions: {
css: {},
postcss: {
plugins: [ require('postcss-px2rem')({ remUnit: 37.5 })
]
}
}
}
}
和我们正常创建项目相同,这里通过vue-cli3脚手架进行创建
vue create 项目name
选择自己需要的依赖并进行下一步
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
// return originalPush.call(this, location).catch((err) => err)
// }
const routes = [
{
path: '/login',
name: 'login',
component: () => import('./views/index.vue'),
// component:()=>import('./reset.vue'),
meta: {
title: '这里是动态title'
},
children: [
/*
单页面应用的写法
{
path: 'reset',
name: 'reset',
component: () => import('./reset.vue')
},
*/
// ***多页面的写法
{
path: 'editJobs',
components: {
'editJobs': () => import('./views/reset.vue'),
},
},],
},
// {
// path: '/',
// redirect: '/'
// }
]
export default new VueRouter({
mode: 'hash',
base: process.env.BASE_URL,
routes
})
// 打包多入口文件基本配置
function getPagesInfo() {
let pages = {}
const glob = require('glob') // 引入glob模块,用于扫描全部src/pages/**/main.js(返回的是一个数组)
glob.sync('src/pages/**/main.js').forEach((entry, i) => {
let name = entry.slice(10, -8)
pages[name] = {
entry: entry,
template: 'public.index.html',
filename: name + '.html',
title: '',
chunks: ["chunk-vendors", "chunk-common", name]
}
})
return pages
}
module.exports = {
pages: getPagesInfo(),
publicPath: './kk',
assetsDir: 'static',
};
npm i -S vue-wechat-title
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
<template>
<!-- 动态设置title -->
<div id="app" v-wechat-title='$route.meta.title'>
<router-view/>
</div>
</template>
const routes = [
{
path: '/login',
name: 'login',
component: () => import('./views/index.vue'),
meta: {
title: '这里是动态title'
},
children: [
// ***多页面的写法
{
path: 'editJobs',
components: {
'editJobs': () => import('./views/reset.vue'),
},
},],
},
]
<template>
<div>
login
<router-link :to="{ name: 'reset' }" tag="li">我的收藏</router-link>
这里的name对应的是route配置里的名字(别忘了地址连里面的path)
<router-view name="editJobs">待完善信息</router-view>
</div>
</template>
// 打包多入口文件基本配置
let developmentPath = './';//开发环境-npm run serve时引用文件路径
let productionPath = './';//生产环境-npm run build打包后引用文件路径
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')//生产环境取消打印
const CompressionWebpackPlugin = require('compression-webpack-plugin')//gzip压缩
const productionGzipExtensions = ['js', 'css']
const Version = 'V6.1'
const Timestamp = new Date().getTime()
function getPagesInfo() {
let pages = {}
const glob = require('glob') // 引入glob模块,用于扫描全部src/pages/**/main.js(返回的是一个数组)
glob.sync('src/pages/**/main.js').forEach((entry, i) => {
let name = entry.slice(10, -8)
pages[name] = {
entry: entry,
template: 'public.index.html',
filename: name + '.html',
title: '',
chunks: ["chunk-vendors", "chunk-common", name]
}
})
return pages
}
// 打包相关
module.exports = {
pages: getPagesInfo(),//多页面应用配置
publicPath: process.env.NODE_ENV === 'production' ? productionPath : developmentPath, // 基本路径-引用文件的路 __dirname + '/server/dist', //build之后静态文件输出路径
assetsDir: 'static',//静态资源大包位置
outputDir: __dirname + '/server/dist', //build之后静态文件输出路径
lintOnSave: process.env.NODE_ENV !== 'production',// 打包的时候eslint-loader检查
productionSourceMap: false,//source map 检查
// 启动服务器
devServer: {
index: '/login.html', //默认打开文件
open: true, //自动打开浏览器
host: 'localhost', //默认打开域名
port: 8080, //默认打开端口号
https: false, //开启关闭https请求
hotOnly: false, //热更
// 反向代理
proxy: {
// 配置跨域
'/api': {
target: 'http://dev.aabb.cn:8082/', //代理地址,这里设置的地址会代替axios中设置的baseURL
ws: true, //// proxy websockets
changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
pathRewrite: { //pathRewrite方法重写url
'^/api': '/',
},
},
},
},
// webpack配置 链式
chainWebpack: (config) => {
// 1、取消预加载增加加载速度
config.plugins.delete('preload')
config.plugins.delete('prefetch')
// 2、vue中使用SVG图标,并且想批量导入,然后需要使用的时候直接添加就可以
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]',
})
.end()
// 3、图片处理
const imagesRule = config.module.rule('images')
imagesRule.uses.clear() //清除原本的images loader配置
imagesRule
.test(/\.(jpg|gif|png|svg)$/)
.exclude.add(path.join(__dirname, '../node_modules')) //不对node_modules里的图片转base64
.end()
.use('url-loader')
.loader('url-loader')
.options({ name: 'img/[name].[hash:8].[ext]', limit: 6000000 })
config.optimization.splitChunks({
cacheGroups: {
vendors: {
name: 'chunk-vendors',
minChunks: pageNum,
test: /node_modules/,
priority: -10,
chunks: 'initial',
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true,
},
},
})
},
// webpack配置
configureWebpack: (config) => {
// 为生产环境修改配置
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
// 1、取消打印
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_debugger: true,//生产环境自动删除debugger
drop_console: true, //生产环境自动删除console
},
warnings: false,
},
sourceMap: false, //关掉sourcemap 会生成对于调试的完整的.map文件,但同时也会减慢打包速度
parallel: true, //使用多进程并行运行来提高构建速度。默认并发运行数:os.cpus().length - 1。
}),
// 2、gzip压缩
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8,
})
)
}
// 在这里配置后,减少了压缩的包内容,需要在public/index.html通过cdn方式再引入,注意对应的版本
config.externals = {
vue: 'Vue',
'vue-router': 'VueRouter',
vuex: 'Vuex',
axios: 'axios',
jquery: '$',
moment: 'moment',
'mint-ui': 'MINT'
},
// 别名配置
Object.assign(config, {
// 开发生产共同配置
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@c': path.resolve(__dirname, './src/components'),
'@p': path.resolve(__dirname, './src/pages')
}
}
}),
config.output.filename = `[name].${Version}.${Timestamp}.js` //打包生成的文件
config.output.chunkFilename = `[name].${Version}.${Timestamp}.js`
},
// css相关
css: {
loaderOptions: {
// 配置全局sass
scss: {
additionalData: `@import "@/assets/css/reset.scss";@import "@/assets/css/globle.scss";` //注意配置的键名
},
// lib-flexible
postcss: {
plugins: [
//remUnit这个配置项的数值是多少呢??? 通常我们是根据设计图来定这个值,原因很简单,便于开发。
//假如设计图给的宽度是750,我们通常就会把remUnit设置为75,这样我们写样式时,可以直接按照设计图标注的宽高来1:1还原开发。
require('postcss-px2rem')({
remUnit: 37.5
})
]
}
}
},
parallel: require('os').cpus().length > 1, // 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。
pwa: {}, // PWA 插件相关配置
pluginOptions: {}, // 第三方插件配置
};
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只
我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA