model.rb 1.16 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

  def save
    @id = @storage.create_id(self) unless @id
    @storage.write(self)
  end

  def update
    @storage.write(self)
  end

  def to_sym
    self.class.to_s.to_sym
  end

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