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

本文介绍在Rails应用中如何定义全局变量和常量,包括不同环境下的配置方法。阐述了将这些变量放置在config/environment.rb文件中的原因,并提到了特定于环境的变量应放在各自的环境配置文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值