Where to put Global variables in Rails 3

ぃ、小莉子 提交于 2019-12-17 07:21:39

问题


I used to put Global variables in environment.rb with my Rails 2.3.8 application such as:

MAX_ALLOWD_ITEMS = 6

It doesn't seem to work in Rails 3. I tried putting it in application.rb and that didn't help.

What do you suggest?


回答1:


If you have already tried restarting your server as Ryan suggested, try putting it in your application.rb like this:

module MyAppName
  class Application < Rails::Application
    YOUR_GLOBAL_VAR  = "test"
  end
end

Then you can call it with the namespace in your controllers, views or wherever..

MyAppName::Application::YOUR_GLOBAL_VAR

Another alternative would be using something like settingslogic. With settingslogic, you just create a yml config file and a model (Settings.rb) that points to the config file. Then you can access these settings anywhere in your rails app with:

Settings.my_setting



回答2:


I usually go with application_helper.rb This is what it looks like:

module ApplicationHelper
  def my_global_variable 
    my_global_variable = "Helloworld!"      
  end
end

Then I can put in my_global_variable anywhere as a function.




回答3:


If you are truly defining it in config/environment.rb like you say, the only way I can duplicate your problem is by running up a server using rails server, then putting in the variable to config/environment.rb, referencing it in a view or controller somewhere and then trying to load that specific part of my application.

If I stop the server and start it again and again try to access that view or controller then it works. I reckon you just haven't restarted your server.




回答4:


I normally create inside config/initializers/ a yaml (yml) file with all the global site settings. remember to restart the server each time you change anything.




回答5:


I don't know if the solution of adding variables to environment.rb would in fact work in Rails3 - to be specific, if you haven't defined the variable inside a module definition like so:

module MyConfig
  Max_ints = 5
end

you won't be able to just use Max_ints, if you just include it as a bare definition. Or at least that's what I found happened when I experimented with this. I also think the suggestion to use the initializers/ folder is possibly a better solution in terms of ease of use. See Permanent variable in Rails



来源:https://stackoverflow.com/questions/3598785/where-to-put-global-variables-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!