2014-10-08 66 views
0

在Sinatra(使用Sinatra :: Configfile)中,使用類似settings.foo這樣的簡單設置很容易,但是如果需要將設置置於層次結構中,則不太明顯以簡單直接的方式。在Sinatra中動態獲取嵌套設置

這是痛苦的冗長:

get '/test' do 
    case settings.environment 
    when :production 
    settings.production['foo'] 
    else 
    settings.development['foo'] 
    end 
end 

更接近於這將是更好的,但是,這並不工作:

get '/test' do 
    settings[settings.environment]['foo'] 
end 
+0

'settings.send(settings.environment)['foo']''? – 2014-10-08 22:40:52

+0

是的,我想過這樣做,但我假設有一個更標準(和簡單/優雅/可讀)Sinatra的方式做到這一點... – iconoclast 2014-10-08 22:42:32

回答

1

您是否在尋找configure

set :foo, "default value\n" # or explicitly set for each environment 
          # with different configure blocks 

configure :production do 
    set :foo, "production\n" 
end 

get '/test' do 
    settings.foo 
end 
+0

沒有:我想這些配置在一個YAML文件。 – iconoclast 2014-10-13 18:13:39

+0

@iconoclast是否使用[Sinatra :: ConfigFile](http://www.sinatrarb.com/contrib/config_file.html)或類似的東西? 'settings'本身並不使用Yaml。 – matt 2014-10-13 19:21:36

+0

是的,我忘了提到這一點。抱歉。 – iconoclast 2014-10-13 23:02:22

1

我相信這就是你要去的。

在您的Sinatra應用程序的頂部添加以下內容。

require 'sinatra/config_file' 
config_file './config/config.yml' # Point to wherever you want to store your config.yml 

# Within your config.yml specify per environment settings; very similar to Rails 
development: 
    database: sqlite://../bigtunadev.db 
    cipher: lamecipher4dev 
    oracle: 
    user: oracle_user 
    password: oracle_password 
    db2: 
    user: db2_user 
    password: db2_password 
    mysql: 
    user: mysql_user 
    password: mysql_password 

production: 
    database: sqlite://../bigtunaprod.db 
    cipher: [email protected]@w3s0m3c1p43r 

默認情況下只支持test, production, and development環境。

如果你想添加額外的環境,那麼你將不得不在你的配置中覆蓋它,如下所示。

set :environments, %w{development test production staging} 

這將直接顯示當前環境設置的屬性。


請注意在開發部分,我已經添加了其他嵌套。

多級嵌套必須作爲散列來訪問,所以它看起來如下所示。

settings.oracle["user"]

+0

是的,我很高興知道我給出的例子,但我想要一個獲得分層信息的廣義方式。例如,想象一個基於Sinatra的API從不同的RDBMS中提取數據。我可能需要一個請求上的oracle.user和oracle.password,但另一個請求上需要db2.user和db2.password。 – iconoclast 2014-10-13 18:18:25

+0

如果我正確理解你想要做的事情,你應該能夠遵循我給出的原始示例,並擴展YAML嵌套。唯一的奇怪之處在於,除了第一個嵌套級別之外,它必須作爲散列來訪問,而不是使用點符號。我在上面的示例中添加了一些額外的信息,希望能夠澄清。如果這仍然不是你正在尋找的,也許我們可以在私人聊天室中跟進,這樣線程就不會持續太久。 – bigtunacan 2014-10-14 00:36:14

+0

我不想做'settings.oracle [「user」]'因爲代碼需要是動態的。我需要像'settings [「database」] [「user」]''。 – iconoclast 2014-10-14 02:42:53

3

您可以使用send調用方法使用字符串對象上。

get '/test' do 
    settings.send(settings.environment.to_s)['foo'] 
end