Rails 提供三種預設執行環境,各擁有獨立配置:
# WEBrick/Mongrel
ruby script/server -e development # 或 test, production
# Apache + FastCGI / Passenger
SetEnv RAILS_ENV production # 在虛擬主機設定環境變數
config/database.yml 新增區段(如 staging:)config/environments/ 建立 staging.rb-e staging 或 RAILS_ENV=stagingconfig/database.yml 使用 YAML 格式,三區段對應三環境:
development:
adapter: mysql
database: depot_development
username: root
password:
host: localhost
test:
adapter: mysql
database: depot_test
username: root
password:
host: localhost
production:
adapter: mysql
database: depot_production
username: root
password: prod
host: wibble
# 同環境不同資料庫
development:
development_mysql:
adapter: mysql
database: depot_development
host: localhost
development_sqlite:
adapter: sqlite3
dbfile: db/depot.sqlite3
# 程式碼中切換
ActiveRecord::Base.establish_connection(:development_mysql)
config/environment.rb 為共用配置,啟動時再載入 config/environments/#{RAILS_ENV}.rb。
$LOAD_PATH)# 自動加入載入路徑
test/mocks/#{RAILS_ENV}/ # 測試模擬物件優先覆寫
app/models/
app/controllers/
app/helpers/
app/apis/
components/
config/
lib/
vendor/
vendor/rails/*
# environment.rb 內建初始化
RAILS_DEFAULT_LOGGER = Logger.new("log/#{RAILS_ENV}.log")
ActiveRecord::Base.logger = RAILS_DEFAULT_LOGGER
ActionController::Base.logger = RAILS_DEFAULT_LOGGER
ActionMailer::Base.logger = RAILS_DEFAULT_LOGGER
ActionController::Base.view_path = "app/views"
ActionMailer::Base.template_root = "app/views"
詳細參數請參考 config/environment.rb 註解與 Rails API 文件,常用者包括:
config.cache_classes:生產環境設 true 避免類別重載config.action_controller.perform_caching:啟用頁面/動作/片段快取config.active_record.schema_format::ruby 或 :sql 控制 schema 匯出格式config.time_zone:設定應用程式預設時區