Where to put Global variables in Rails 3

后端 未结 5 1752
旧时难觅i
旧时难觅i 2020-11-30 03:25

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

相关标签:
5条回答
  • 2020-11-30 03:47

    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
    
    0 讨论(0)
  • 2020-11-30 03:48

    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.

    0 讨论(0)
  • 2020-11-30 03:50

    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.

    0 讨论(0)
  • 2020-11-30 03:59

    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.

    0 讨论(0)
  • 2020-11-30 04:08

    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 讨论(0)
提交回复
热议问题