【问题标题】:What's the best way to manage real-time configuration variables with Ruby on Rails?使用 Ruby on Rails 管理实时配置变量的最佳方式是什么?
【发布时间】:2010-11-09 14:19:42
【问题描述】:

我知道 YAML 和 rails-settings 之类的插件,但这些对于需要实时更改的配置设置都没有用处。

例如,假设我将 MAX_ALLOWED_REGISTERED_USERS 设置为 2000,但我想将其提高到 2300。对于典型的“配置”或 YAML 解决方案,这将涉及更改配置文件并重新部署。我更喜欢数据库支持的 RESTful 方法,我可以只更改键/值对。

想法?

【问题讨论】:

    标签: ruby-on-rails configuration key-value


    【解决方案1】:

    我使用类似这样的配置模型:

    # == Schema Information
    # Schema version: 20081015233653
    #
    # Table name: configurations
    #
    #  id          :integer         not null, primary key
    #  name        :string(20)      not null
    #  value       :string(255)
    #  description :text
    #
    
    class InvalidConfigurationSym < StandardError; end
    
    class Configuration < ActiveRecord::Base
      TRUE  = "t"
      FALSE = "f"
    
      validates_presence_of   :name
      validates_uniqueness_of :name
      validates_length_of     :name, :within => 3..20 
    
      # Enable hash-like access to table for ease of use.
      # Raises InvalidConfigurationSym when key isn't found.
      # Example:
      #   Configuration[:max_age] => 80
      def self.[](key)
        rec = self.find_by_name(key.to_s)
        if rec.nil?
          raise InvalidConfigurationSym, key.to_s
        end
        rec.value
      end
    
      # Override self.method_missing to allow
      # instance attribute type access to Configuration
      # table. This helps with forms.
      def self.method_missing(method, *args)
        unless method.to_s.include?('find') # skip AR find methods
          value = self[method]
          return value unless value.nil?
        end
        super(method, args)
      end
    end
    

    我是这样使用它的:

    class Customer < ActiveRecord::Base
      validate :customer_is_old_enough?
    
      def customer_is_old_enough?
        min_age = Date.today << (Configuration[:min_age].to_i * 12)
        self.errors.add(:dob, "is not old enough") unless self.dob < min_age
      end
    end
    

    我不太满意的一件事是必须像示例中那样调用#to_i,但由于它到目前为止对我有用,所以我没有过多考虑重新设计它。

    【讨论】:

      【解决方案2】:

      Moneta 可能会满足您的需求,它是一个具有可配置后端的键/值存储系统:

      http://yehudakatz.com/2009/02/12/initial-release-of-moneta-unified-keyvalue-store-api/

      【讨论】:

        【解决方案3】:

        如果您正在运行多服务器应用程序,则需要集中存储可变配置(除非您不介意不同服务器具有不同配置)

        如上所述,Moneta 是一个不错的选择,尽管我敢打赌 mecached 与 Rails 应用程序一起部署得更广泛。

        【讨论】:

          【解决方案4】:

          这是一个天真的建议:创建一个数据库表、迁移和 ActiveRecord-model,并将您的配置视为数据库中的任何其他实体,减去控制器和视图。只是一个想法。

          也许将这些数据放在 memcached 中,如果您太担心会干扰数据库,请让它足够频繁地过期。

          【讨论】:

          • 噢!我基本上复制了马特黑利的答案。好吧,我想我的答案是他在没有告诉懒惰/随意的读者(我)他要去哪里的情况下启动的所有代码的摘要。
          猜你喜欢
          • 2011-05-06
          • 1970-01-01
          • 1970-01-01
          • 2010-09-20
          • 2010-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-25
          相关资源
          最近更新 更多