model.rb 1.33 KB
module DsAdmin::Model
  include Enumerable

  DsAdmin::Model.autoload(:User, 'model/user')
  DsAdmin::Model.autoload(:Group, 'model/group')
  DsAdmin::Model.autoload(:Site, 'model/site')
  DsAdmin::Model.autoload(:MailAliasRole, 'model/mail_alias_role')
  DsAdmin::Model.autoload(:MailAliasPerson, 'model/mail_alias_person')
  DsAdmin::Model.autoload(:MailAccount, 'model/mail_account')

  def (DsAdmin::Model).storage=(storage)
    @@storage = storage
  end

  def (DsAdmin::Model).storage
    @@storage
  end

  attr_accessor :id

  def initialize(args = {})
    @id = args[:id] if args[:id]
  end

  def all
    @@storage.config.model = self

    @@storage.map do |data| 
      self.class.new(data)
    end
  end

  def each(&block)
    all.each(&block)
  end

  def load(id)
    self.class.new(_load(id))
  end

  def load!(id)
    initialize(_load(id))
  end

  ##
  # used to save either new or changed models
  #
  # @storage is free to change an already existent storage id
  # for organizational, indexing or other reasons thus it 
  # always has to be stored back into @id
  #
  def save
    @id = @storage.write(self)
  end

  def config_key
    self.class.to_s.to_sym
  end

  protected
  def _load(id)
    @@storage.config.model = self

    data = @@storage.find {|data| data[:id] == id}
    throw "unknown id (#{id})" unless data
    data
  end
end