Where can I store site-wide variables in Rails 4?

前端 未结 5 1120
眼角桃花
眼角桃花 2020-12-13 14:41

I am new to Rails and come from a ColdFusion background, where we would store global / site-wide variables in the \'application\' scope. This persists the variable across an

5条回答
  •  佛祖请我去吃肉
    2020-12-13 15:08

    This sounds like a perfect example for configuration values stored in config/environments/production.rb and config/environments/development.rb. Just store any value there:

    config.my_special_value = 'val'
    

    And access it in your application like this:

    Rails.application.config.my_special_value
    

    Always the value of your environment is active.

    If you just want to have a „global“ value, store it in your application controller. All your view controllers are derived from your app controller, so you can save any value there as an instance or class variable:

    class ApplicationController < ActionController::Base
      MY_CONSTANT_VALUE = "foo"
    end
    
    class MyViewController < ApplicationController
      def index
        raise MY_CONSTANT_VALUE.inspect
      end
    end
    

    You also could implement an helper:

    # app/helpers/application_helper.rb
    module ApplicationHelper
      FOO = "bar"
    end
    
    # app/controllers/foo_controller.rb
    class FooController < ApplicationController
      def index
        raise FOO
      end
    end
    

提交回复
热议问题