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.

From: http://urgetopunt.com/rails/2009/09/12/yaml-config-with-erb.html

rails中的render,redirect_to和flash

rails中的render和redirect_to我们使用的次数应该很多,写下来算是一个笔记。

首先render是渲染出页面,而redirect_to是跳转。我们写程序有个原则是不要重复造轮子,所以我们如果有一个view模板写出来后经常会有其他的action使用,比如我们写了文章列表的页面模板,然后搜索的页面也用得到,这时使用render来渲染对应的模板,便不用再重写一个搜索的view模板。而redirect_to接受的参数则像link_to,是作为跳转的。而render只可以使用同一个controller的view。

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

所以一般情况下,flash[:error]和redirect_to一起使用,flash.now[:error]则和render配合使用。