2009-07-10 26 views
2

我知道YAML和插件像rails-settings,但这些对于需要实时更改的配置设置都是非常有用的。例如,假设我将MAX_ALLOWED_REGISTERED_USERS设置为2000,但我想将其提高到2300.对于典型的“配置”或YAML解决方案,这将涉及更改配置文件并重新部署。我更喜欢数据库支持的RESTful方法,我可以只更改一个键/值对。使用Ruby on Rails管理实时配置变量的最佳方式是什么?

想法?

回答

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一样,但由于它迄今为止对我有用,所以我没有在重新设计它时考虑太多。

0

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

正如上面贴莫尼塔是一个不错的选择,虽然我愿意下注mecached与Rails应用程序一起更广泛地部署。

0

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

也许把这些数据放在memcached中,如果你太担心干扰数据库的话,它可能会过期。

+0

Doh!我基本上重复了Matt Haley的回答。那么,我想我的回答是他没有告诉懒惰/随便的读者(我)他去哪里的所有代码的总结。 – Roboprog 2009-07-11 00:18:21

相关问题