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,如需转载请自行联系原作者
 
相关文章
|
3月前
|
存储 Swift
在Swift编程语言中,变量(Variable)和常量(Constant)
在Swift编程语言中,变量(Variable)和常量(Constant)
35 1
|
21小时前
|
Python
Day4作用域,Python关键字global和nonlocal使用
作用域,Python关键字global和nonlocal使用
4 0
|
2月前
|
JavaScript
报错:npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
报错:npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
|
8月前
|
安全
python--global、nonlocal、闭包
python--global、nonlocal、闭包
|
9月前
|
存储 缓存 监控
【2023】ansible-variables变量详解
【2023】ansible-variables变量详解
90 0
|
10月前
|
Python
Python 关键字global全局变量详解
Python 关键字global全局变量详解
|
JavaScript
eslint全局变量报错 xxx is not defined
eslint全局变量报错 xxx is not defined
420 0
Python 中的关键字,global和nonlocal
Python 中的关键字,global和nonlocal
|
安全 PHP 开发者
Global 关键字|学习笔记
快速学习 Global 关键字
88 0
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
99 0