开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 24 天,点击查看活动详情”
五、Rails 的配置
Rails 运行时的配置都可以由 config 目录下的配置文件来控制。config 目录中的 environments 目录包含了 3 个文件:development.rb、test.rb 和 production.rb,正是这三个文件控制了 Rails 在 3 中运行模式中的表现。
在 development.rb 中可以看到这样的设置:
# In the development environment your application's code is reloaded any time
# it changes. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false # 不允许缓存
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable server timing
config.server_timing = true
而在 production.rb 中则看到相反的配置
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
这些参数都是根据实际情况进行修改的。如果希望应用上线后,还能够即时反应模型控制器代码,则可以对 cache 配置做相应的修改。
config 目录下还有几个配置文件非常重要,比如 environment.rb、database.yml、boot.rb 和 routes.rb。
environment.rb 是用于全局的环境变阿玲设置,它是开发测试和生产模式共用的,通常会在文件中方式ActionMailer 发送邮件的参数以及加载的库的引用等。
database.yml 是用于配置 ActiveRecord 与数据库的连接参数,database.yml 中可以定义多个连接配置,默认情况下又3中配置,development,test 和 production,分别对应了 Rails 应用运行的3种模式,在实际的开发中,如果使用了多个数据库,可以在 database.yml 中添加多个连接配置,然后在模型类中使用 establish_connection 方法指定使用的数据库连接。
比如定义的第二个 MySQL 数据库的连接配置如下:
more_database:
adapter: mysql2
encoding: utf8mb4
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: root
password: root
host: root
如果需要使用该数据数据库连接,创建的模型类代码如下:
class User < ApplicationRecord
establish_connection :more_database
end
boot.rb 文件是 Rails 用来引导启动的文件,这个文件不能被修改该。
routes.rb 是用于 URL 路由映射的配置。在项目目录下命令行中使用 rails routes 可以查看应用中的所有路由