2009-07-10 23 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

相關問題