在Sinatra中靈活的配置Environments
在Sinatra中有三個預先定義的環境屬性值,包括:development, test, production.
這個目前所處的環境的值還可以通過RACK_ENV這個環境變量來設定。如果什麼都不設定,預設就是develpment。
之是以要區分不同環境的值,主要是我們在不同的環境下需要采用不同的配置。例如:開發環境采用postgres,測試環境運作自動化測試用sqlite,産品環境部署需要用到Cloud Foundry上的Postgres Service。
首先,使用configure來設定不同環境的配置。比如上面的資料庫配置的例子:
configure :development do
DataMapper.setup(:default, "postgres://localhost/test")
DataMapper.finalize.auto_upgrade!
end
configure :test do
DataMapper.setup(:default, "sqlite::memory:")
end
configure :production do
load_postgres_on_cloudfoundry
DataMapper.finalize.auto_upgrade!
end
其中,production環境中load_postgres_on_cloudfoundry方法負責具體擷取和初始化Cloud Foundry上資料庫的配置。Rack應用部署到Cloud Foundry的時候,環境變量RACK_ENV會設定為production。
在本地開發調試的時候可以設定RACK_ENV這個環境變量來制定,也可以通過指令行參數來指定。例如: ruby my_app.rb -e [ENVIRONMENT]
還可以在代碼中通過set指令設定,例如:set :environment, :production。如果不用set設定,:environment預設就是ENV['RACK_ENV']
同時在Sinatra的應用中,我們可以通過預定義的development?, test?和production?方法來檢查和判斷目前的環境的設定。
------------------------------------------------------------------------------------------------------
上面這些就是最常見的使用方式。接下來介紹一個Sinatra的一個擴充config_file,可以友善我們使用單獨的YAML檔案來配置不同的環境屬性。
它可以自動發現配置檔案中的設定,并且采用跟目前的環境對應的屬性設定。在應用中我們可以通過settings來通路這些配置。
需要先安裝:gem install sinatra-contrib
使用方法:先寫一個config.yml檔案
greeting: Welcome to my file configurable application
在典型的Sinatra應用中讀取greeting的值:
require "sinatra"
require "sinatra/config_file"
config_file 'path/to/config.yml'
get '/' do
@greeting = settings.greeting
haml :index
end
# The rest of your classic application code goes here...
在子產品化的Sinatra的應用中:
require "sinatra/base"
require "sinatra/config_file"
class MyApp < Sinatra::Base
register Sinatra::ConfigFile
config_file 'path/to/config.yml'
get '/' do
@greeting = settings.greeting
haml :index
end
# The rest of your modular application code goes here...
end
上面的例子是最簡單的用法,下面再說明一下如何針對不同的環境分别進行配置:
方法一:
development:
foo: development
bar: bar
test:
foo: test
bar: bar
production:
foo: production
bar: bar
方法二:
foo:
development: development
test: test
production: production
bar: bar
不管采用那種方法,setting.foo可以取得對應的環境的名稱,settings.bar的值為bar
關于環境的配置,最後一點是如果我們有除了development, test, production之外更多的環境需要配置,比如:staging環境。
我們可以通過設定environments來增加更多的環境。
例如:
set :environments, %w{development test production staging}
參考文檔:
1.http://www.sinatrarb.com/contrib/config_file.html