2009-12-08 37 views
1

如果我为web管理员设置了一些配置,例如每页帖子数,一些枚举显示选择。我应该如何在db中保存这些设置?我应该序列化并保存为blob。保持Web应用程序配置的最佳方式是什么?

感谢,


我使用的轨道,我想它动态地改变通过web界面此设置,所以我觉得environment.rb中不符合这一情况。所以我应该有一个额外的表格,包含两个元组作为名称,值?

+1

您使用的是什么技术?一些语言/框架内置了解决这个问题的解决方案... – NDM 2009-12-08 10:43:40

+0

我在rails上使用ruby作为框架 – sarunw 2009-12-09 18:06:14

回答

0

,你可以在你的数据库来存储键值对创建一个表。

1

大多数语言/框架都有一个排序配置文件。如ASP中的web.config或RoR中的environment.rb文件。你可以使用其中之一。

或者在数据库中存在关键值对表失败。

如果你想通过网站动态做到这一点,我一定会去关键的价值对表。

1

对于动态配置值,您应该创建一个名为Configuration with key和values的模型。我通常有多个值列(数字,字符串和日期),然后调用适当的配置方法。

对于“枚举”,您应该创建具有外键关系的查找表,并将其添加到其中。例如,如果您有Post模型,并且想要枚举类别,则应使用Post belong_to :categoryCategory has_many :posts

1

使用YAML文件。 YAML比XML更简单。

在“config”目录下创建一个名为“config.yml”的文件。并使用YAML :: load()加载文件。您可以通过将第一级命名为环境(例如,生产,开发,测试)来为每个环境进行设置。

请参阅this episode of RailsCasts for details

0

这就是我使用的。从其他地方得到了这个想法,但实施是我的。

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 

我没有找到一个模式是这里的正确的解决方案。忘记数据库被窃听,能够实例化控制应用程序配置的东西的想法是没有意义的。更何况你实现它?每个元组的实例?!它应该是一个单身类。

相关问题