What is the best way to store app specific configuration in rails?

后端 未结 6 622
心在旅途
心在旅途 2020-12-30 14:56

I need to store app specific configuration in rails. But it has to be:

  • reachable in any file (model, view, helpers and controllers
  • environment specifi
6条回答
  •  旧巷少年郎
    2020-12-30 15:20

    The most basic thing to do is to set a class variable from your environment.rb. I've done this for Google Analytics. Essentially I want a different key depending on which environment I'm in so development or staging don't skew the metrics.

    This is how I did it.

    In lib/analytics/google_analytics.rb:

    module Analytics
      class GoogleAnalytics
        @@account_id = nil
    
        cattr_accessor :account_id
      end
    end
    

    And then in environment.rb or in environments/production.rb or any of the other environment files:

    Analytics::GoogleAnalytics.account_id = "xxxxxxxxx"
    

    Then anywhere you ned to reference, say the default layout with the Google Analytics JavaScript, it you just call Analytics::GoogleAnalytics.account_id.

提交回复
热议问题