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
|
# File 'lib/lib/base.rb', line 2
def cattr name = nil, opts = {}, &block
if name
unless opts.class == Hash
raise ArgumentError, 'Options are not a Hash'
end
if block
opts[:default] = block
end
if opts[:class]
define_singleton_method('%s=' % name) do |arg|
CattrProxy.new(self).send('%s=' % name, arg)
end
define_singleton_method(name) do |arg = :_nil|
if arg == :_nil
CattrProxy.new(self).send(name)
else
CattrProxy.new(self).send('%s=' % name, arg)
end
end
end
if opts[:instance]
define_method('%s=' % name) do |arg|
CattrProxy.new(self.class).send('%s=' % name, arg)
end
define_method(name) do
CattrProxy.new(self.class).send(name)
end
end
supported = [:default, :class, :instance]
invalid = opts.keys - supported
if invalid.first
raise ArgumentError, 'Invalid argument :%s, supported: %s' % [invalid.first, supported.join(', ')]
end
CattrProxy.new(self).send('%s=' % name, opts[:default])
else
CattrProxy.new(self)
end
end
|