0

サーバー オプションの構成設定を保持するモデルを開発しています。サーバー オプションの数と種類が変わるので、それを行う 2 つの方法の長所と短所について意見を求める必要があります。Rails ActiveRecord データベースとは別にこれを行っています。データベースとのやり取りはすべて、ファイル システムと手動で行う予定です。

最初に、指定された各サーバーの必要に応じてモデルに属性を動的に作成させます。(これが可能な限り...私は前にそれをやったことがありません)

次に、サーバー オプションのキーとサーバー設定の値を持つ単一のハッシュを作成します。

2番目の方が実装しやすいと思いますが、それが正しい方法かどうかわかりませんか? 動的属性を使用する方がクリーンなようです。

これを行うための経験則はありますか?

4

2 に答える 2

4

Railsのストア機能について知っていますか?

http://api.rubyonrails.org/classes/ActiveRecord/Store.html

基本的に、次のように書くことができます。

class Server < ActiveRecord::Base
  store :options
end

オプション列とタイプテキストを使用して、新しい移行も作成する必要があります。

これで、次のように'options'ストアに値を追加して読み取ることができます。

server_instance.options[:ip] = '10.0.1.7'
server_instance.options[:ip] # returns the IP.

ストアコールにアクセサオプションを追加して、これをクリーンアップすることもできます。

class Server < ActiveRecord::Base
  store :options, accessors: [ :ip, :port ]
end

これで、ip&portを通常の属性として使用できます。

server_instance.ip = '10.0.1.7'
server_instance.ip # returns the IP.
于 2012-03-09T18:58:49.350 に答える
1

あなたのために何かを作りました。

これがどのように機能するかです。

s = Settings.new(SettingsFileManager.new(some_file))

s.ip # returns whats in the file.
s.ip = 10.0.0.1 # overrides the new value.

ファイルとのやり取りの方法はまだ書いていませんので、適切なSettingsFileManagerを作成する必要があります。

どちらかといえば、それはあなたに始めるための良い基盤を与えるはずです。しかし、私は主に私がルビーについて知っていることを確認するためのテストとしてそれを書きました。それはいくつかのややトリッキーなものを使用しているので。

いくつかのテストでgithubでもホストしました。

class Settings

  attr_accessor :settings

  def initialize(file_writer)
    @file_writer = file_writer
    read_settings_to_new_hash
  end

  def read_settings_to_new_hash
    @settings = fabricate_hash
    @settings.replace(@file_writer.read_keys)
  end

  def fabricate_hash
    InterceptedHash.new( &hash_saved_proc )
  end

  def hash_saved_proc
    Proc.new do |key, value|
      @file_writer.write_key(key, value)
    end
  end

  def method_missing(m, *args, &block)
    if @settings.has_key?(m) || args[0]
      if args[0]
        @settings[m.to_s.sub("=","").to_sym] = args[0]
      else
        @settings[m]
      end
    else
      raise "unknown setting"
    end
  end

end

# Not implemented. This should continue the logic to interact with whatever you want.
class SettingsFileManager
  def initialize(file)
    @file = file
  end

  # write the key and its value somewhere.
  def write_key(key, value)
    puts 'write_key', key, value
  end

  # should return hash of keys.
  def read_keys
    puts 'read_keys'
    Hash.new
  end
end

class InterceptedHash < Hash
  def initialize(&block)
    super
    @block = block
  end

  def store(key, value)
    super(key, value)
    @block.call(key, value)
  end

  def []=(key, value)
    store(key, value)
  end
end
于 2012-03-13T21:42:27.400 に答える