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

后端 未结 6 574
心在旅途
心在旅途 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:09

    I was helping a friend set up the solution mentioned by Ricardo yesterday. We hacked it a bit by loading the YAML file with something similar to this (going from memory here):

    require 'ostruct'
    require 'yaml'
    require 'erb'
    #config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml"))
    config = OpenStruct.new(YAML.load(ERB.new(File.read("#{RAILS_ROOT}/config/config.yml")).result))
    env_config = config.send(RAILS_ENV)
    config.common.update(env_config) unless env_config.nil?
    ::AppConfig = OpenStruct.new(config.common)
    

    This allowed him to embed Ruby code in the config, like in Rhtml:

    development:
      path_to_something: <%= RAILS_ROOT %>/config/something.yml
    
    0 讨论(0)
  • 2020-12-30 15:10

    Look at Configatron: http://github.com/markbates/configatron/tree/master

    I have yet to use it, but he's actively developing it now, and looks quite nice.

    0 讨论(0)
  • 2020-12-30 15:14

    I found a good way here

    0 讨论(0)
  • 2020-12-30 15:14

    Use environment variables. Heroku uses this. Remember that if you keep configuration in the codebase, anyone with access to the code has access to any secret configuration (aws api keys, gateway api keys, etc).

    daemontool's envdir is a good tool for setting configuration, I'm pretty sure that's what Heroku uses to give application their environment variables.

    0 讨论(0)
  • 2020-12-30 15:18

    I have used Rails Settings Cached.

    It is very simple to use, keeps your configuration values cached and allows you to change them dynamically.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题