Rails Constant and Global Variables(Rails的常量和全域變數)

來源:互聯網
上載者:User
在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.