Using ERB in YAML Configuration File

A while back in Railscast #85 Ryan Bates demonstrated how to add a YAML-based configuration file to a Rails application. You start with the configuration file — say RAILS_ROOT/config/app_config.yml — containing your configuration data:

And then you load the file from an initializer — say RAILS_ROOT/config/initializer/load_config.rb — containing the following:

And from then on a Hash named APP_CONFIG will be available throughout your application containing the configuration specific to the environment in which your application is running, i.e., development, test or production.

But what if you want to dynamically configure one or more values in your configuration file? Other YAML files loaded by Rails such as fixture files or database.yml are processed through ERB before being loaded. Wouldn’t it be nice to be able to do the same in your application configuration file?

As it is Rails will not process those ERB snippets, but you can change that with one small change to your initializer:

Now, instead of loading the file directly, YAML loads the string returned by ERB#result which will contain the contents of the app_config.yml after the ERB snippets have been evaluated.





render的时候我们也许会碰到flash的问题。flash是一条信息,用过以后会自动清掉。用法:flash[:message] = "something",它的原理是写入seesion的一段话,用完后删除,但如果我们用的是render,flash是对这个view模板上一直有效的。所以搜索的flash和列表页的flash混在了一起,搜索完切换到列表页发现flash消息还在显示!这时我们可以使用[:message] = "something",就可以避免此类问题。为什么呢?因为flash.now不是保存在cookie中,而是在request中。