model.rb
1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
def to_h
Hash[instance_variables.map do |var|
[var[1...var.size].to_sym, instance_variable_get(var)]
end]
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