Rails Constant and Global Variables(Rails的常量和全局变量)

简介:
在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


 
本文转自 RubyPdf 的中文博客博客园博客,原文链接: http://www.cnblogs.com/hardrock/archive/2006/09/07/497554.html,如需转载请自行联系原作者
 
相关文章
|
存储 PHP
PHP $GLOBALS 与 global
PHP $GLOBALS 与 global
49 0
|
6月前
|
Python
global和globals的区别
global和globals的区别
|
6月前
|
Python
Python中有效地使用global和globals()来管理全局变量
Python中有效地使用global和globals()来管理全局变量
|
安全
python--global、nonlocal、闭包
python--global、nonlocal、闭包
|
存储 缓存 监控
【2023】ansible-variables变量详解
【2023】ansible-variables变量详解
135 0
|
JavaScript
eslint全局变量报错 xxx is not defined
eslint全局变量报错 xxx is not defined
651 0
Stylus - 变量(Variables)
Stylus - 变量(Variables)
310 0
Stylus - 变量(Variables)
|
Python
python修改全局变量一定要加global吗?
python修改全局变量一定要加global吗?
236 0
python修改全局变量一定要加global吗?
|
Ruby
【Ruby on Rails问题】publish_name.rb文件中定义的变量显示没有定义NameError: uninitialized constant DB_CLASS
在rails项目中,config/initializers/publish_name.rb文件常用来定义的全局变量、全局常量。但是我们虽然在publish_name.rb文件中定义了常量,但是还是显示没有定义。来看一下解决方法。 问题描述: 在publish_name.rb文件中定义了变量DB_CLASS
130 0