开发者

Design Question for Ruby on Rails Project

I'm beginning to work on a new Ruby on Rails application that is a CRUD interface for certain attributes contained in a config file开发者_Go百科. The process will look something like: CRUD RoR App > Database > Export to config file.

My question is what is the optimal way to design this (the back-end part that exports from the DB to the config file). Assuming the config file is on the same server as the RoR app, would I just write separate classes (in /lib) that have methods to read/write to the config file and include/call them in a before_create filter in my models?


It's a really bad idea to create an application that modifies itself when prompted via user-input. It defeats the benefits of version control, and it makes for a lot of confusing bugs.

If you need some user-configurable setting that can't be modified in the source, consider building out a Settings/Config model that stores keys/values in the database and caches them heavily.

Another thing to keep in mind is that Ruby class definitions are executed just like regular code. For example, you can do the following:

class Foo
  if RUBY_VERSION == '1.9.2'
    def self.bar
      # do something 1.9.2 style
    end
  else
    def self.bar
      # do something 1.8.7 style
  end
end

This example shows a more common Ruby-version toggle, but you can do the same thing based on configuration values if they are accessible to the application when the class definition is executed. If you load the class you do this in, you can always load it again if/when config values change to get this benefit.

Essentially this will allow you to have a setting that allows your user to, for example, require that a particular model gets validated with a particular validator that you didn't address in your codebase, provided your model checks for this sort of configuration and defines the validators like I'm saying.

Make sense?


Yes, you can simply treat ConfigFile as a model class that doesn't use ActiveRecord. It can go with your other models (doesn't have to go in /lib).

class ConfigFile #note no inheriting from AR::Base

  def import
    ...
  end

  def export
    ...
  end
end

This class can be the interface to the file, used by your Rails app. I'm not sure about calling it from a before_create though. If you plan to regenerate the entire file each time, you wouldn't want to do that when just one part of it is being updated, unless it is very small.

Do you have the option of determining the format of the config file? Just output model.to_yaml and you're done!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜