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
|
# File 'lib/cim_attributes.rb', line 7
def cim_attr_reader(*args)
raise ArgumentError, 'no args for cim_attr_reader' unless args.size > 0
opts = if args.last.is_a?(Hash)
args.pop
else
{}
end
args.each do |attr|
target, message = *(if self.respond_to? :define_singleton_method
[self, :define_singleton_method]
else
[class << self; self; end, :define_method]
end)
target.send message, attr do
self.instance_variable_get("@#{attr}") || if self.superclass.respond_to?(attr)
self.superclass.send(attr)
else
nil
end
end
target.send message, "#{attr}=" do |val|
self.instance_variable_set("@#{attr}", val)
end
target.send message, "with_#{attr}" do |val, &blk|
if val || (val = self.send(attr))
blk.call(val)
else
raise("no #{attr} defined for #{self} and none passed in")
end
end
self.send :define_method, attr do
self.instance_variable_get("@#{attr}") || self.class.send(attr)
end
self.send :define_method, "#{attr}=" do |val|
self.instance_variable_set("@#{attr}", val)
end
self.send :define_method, "ensure_#{attr}!" do
if !self.send(attr)
raise("no #{attr} defined for #{self}")
end
end
end
end
|