如果我爲web管理員設置了一些配置,例如每頁帖子數,一些枚舉顯示選擇。我應該如何在db中保存這些設置?我應該序列化並保存爲blob。保持Web應用程序配置的最佳方式是什麼?
感謝,
我使用的軌道,我想它動態地改變通過web界面此設置,所以我覺得environment.rb中不符合這一情況。所以我應該有一個額外的表格,包含兩個元組作爲名稱,值?
如果我爲web管理員設置了一些配置,例如每頁帖子數,一些枚舉顯示選擇。我應該如何在db中保存這些設置?我應該序列化並保存爲blob。保持Web應用程序配置的最佳方式是什麼?
感謝,
我使用的軌道,我想它動態地改變通過web界面此設置,所以我覺得environment.rb中不符合這一情況。所以我應該有一個額外的表格,包含兩個元組作爲名稱,值?
如果您使用的是asp.net,則可以使用Web.Config文件。
,你可以在你的數據庫來存儲鍵值對創建一個表。
大多數語言/框架都有一個排序配置文件。如ASP中的web.config或RoR中的environment.rb文件。你可以使用其中之一。
或者在數據庫中存在關鍵值對錶失敗。
如果你想通過網站動態做到這一點,我一定會去關鍵的價值對錶。
對於動態配置值,您應該創建一個名爲Configuration with key和values的模型。我通常有多個值列(數字,字符串和日期),然後調用適當的配置方法。
對於「枚舉」,您應該創建具有外鍵關係的查找表,並將其添加到其中。例如,如果您有Post模型,並且想要枚舉類別,則應使用Post belong_to :category
和Category has_many :posts
。
使用YAML文件。 YAML比XML更簡單。
在「config」目錄下創建一個名爲「config.yml」的文件。並使用YAML :: load()加載文件。您可以通過將第一級命名爲環境(例如,生產,開發,測試)來爲每個環境進行設置。
這就是我使用的。從其他地方得到了這個想法,但實施是我的。
class AppConfig
# Loads a YAML configuration file from RAILS_ROOT/config/. The default file
# it looks for is 'application.yml', although if this doesn't match your
# application, you can pass in an alternative value as an argument
# to AppConfig.load.
# After the file has been loaded, any inline ERB is evaluated and unserialized
# into a hash. For each key-value pair in the hash, class getter and setter methods
# are defined i.e., AppConfig.key => "value"
# This allows you to store your application configuration information e.g., API keys and
# authentication credentials in a convenient manner, external to your application source
#
# application.yml example
#
# :defaults: &defaults
# :app_name: Platform
# :app_domain: dev.example.com
# :admin_email: [email protected]
# :development:
# <<: *defaults
# :test:
# <<: *defaults
# :production:
# <<: *defaults
# :app_domain: example.com
#
# For example will result in AppConfig.app_domain => "dev.example.com"
# when Rails.env == "development"
#
class << self
def load(file='application.yml')
configuration_file = File.join Rails.root, 'config', file
File.open(configuration_file) do |configuration|
configuration = ERB.new(configuration.read).result
configuration = YAML.load(configuration)[Rails.env.to_sym]
configuration.each do |key, value|
cattr_accessor key
send "#{key}=", value
end
end if File.exists? configuration_file
end
end
end
AppConfig.load
創建config/initializers/app_config.rb
和上面的代碼粘貼到它:從我的一個生產項目拉動。我將把它變成寶石。我認爲其他人會發現它很有用。
編輯:剛纔看到你希望編輯配置爲應用程序通過基於Web的界面運行。你可以用這個方法做到這一點,因爲getter和setter方法都是爲每個屬性定義的。
在你的控制器:
def update
params[:configuration].each { |k,v| AppConfig.send "#{k}=", v }
…
end
我沒有找到一個模式是這裏的正確的解決方案。忘記數據庫被竊聽,能夠實例化控制應用程序配置的東西的想法是沒有意義的。更何況你實現它?每個元組的實例?!它應該是一個單身類。
您使用的是什麼技術?一些語言/框架內置瞭解決這個問題的解決方案... – NDM 2009-12-08 10:43:40
我在rails上使用ruby作爲框架 – sarunw 2009-12-09 18:06:14