使用Ruby on Rails管理实时配置变量的最佳方法是什么?

时间:2009-07-10 02:49:01

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

我知道YAML和插件就像rails-settings一样,但这些都不适用于需要实时更改的配置设置。

例如,假设我将MAX_ALLOWED_REGISTERED_USERS设置为2000,但我希望将其设置为2300.使用典型的“配置”或YAML解决方案,这将涉及更改配置文件并重新部署。我更喜欢数据库支持的RESTful方法,我只需更改一个键/值对。

思想?

4 个答案:

答案 0 :(得分:3)

我使用与此类似的配置模型:

# == 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,但是因为它对我有用,所以我没有过多考虑重新设计它。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

如上所述,Moneta是一个不错的选择,虽然我的下注mecached与Rails应用程序一起被更广泛地部署。

答案 3 :(得分:0)

这是一个天真的建议:创建一个数据库表,迁移和ActiveRecord模型,并像处理数据库中的任何其他实体一样处理您的配置,减去控制器和视图。只是一个想法。

也许把这些数据放在memcached中,如果你太担心打扰数据库,它就会经常过期。