开发者

Where to put Global variables in Rails 3

I used to put Global variables in environment.rb with my Rails 2开发者_JS百科.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?


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


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜