在Rails下定义常量和全局变量的方法如下,如果你希望任何环境(开发,测试,产品)下都可以访问的话,则定义在config/environment.rb中
如:
BOOLEN_TRUE=1
如果你希望你的全局变量根据环境来决定,则根据需要在下面的环境中配置
/config/environments/development.rb
/config/environments/test.rb
/config/environments/production.rb

注意,
1> 常量和全局变量必须全部为大写;
2> 设置了全局常量和变量后需重新启动服务器以加载新的设置。


PS. english version

I was recently faced with a common problem that I wanted to share.  During development there are times you need to specifiy a global or constant variable that will be shared throughout the entire application.  In ColdFusion you would normally place something like this in Application.cfm.  In Rails I was uncertain how exactly to approach this.  At first I thought an application.rb file made sense, but the more I thought about it I decided to take advantage of the config files.

Since my global variable was one that would be consistent regardless of environment (dev, test, and prod) I decided to place it in config/environment.rb.  I placed this under the RAILS_GEM_VERSION constant:

# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = ‘1.1.2′
BASE_URL = ‘http://mydomain.com/’

Now referencing this in any view can be done similar to any other variable:

<%= BASE_URL %>

If you need to specify globals that are specific to environment then I recommend placing them in their appropriate config file:

/config/environments/development.rb
/config/environments/test.rb
/config/environments/production.rb


From: http://www.db75.com/new_blog/?p=262


posted on 2006-09-07 15:15  RubyPDF  阅读(4058)  评论(0编辑  收藏  举报