1 module InheritableClassAttributes
2 def self.included(base)
3 base.extend ClassMethods
4 base.module_eval do
5 class << self
6 alias inherited_without_inheritable_class_attributes inherited
7 alias inherited inherited_with_inheritable_class_attributes
8 end
9 end
10 end
11
12 module ClassMethods
13 def inheritable_cattr_readers
14 @inheritable_class_readers ||= []
15 end
16
17 def inheritable_cattr_writers
18 @inheritable_class_writers ||= []
19 end
20
21 def cattr_inheritable_reader(*symbols)
22 symbols.each do |symbol|
23 self.inheritable_cattr_readers << symbol
24 self.module_eval %{
25 def self.#{symbol}
26 @#{symbol}
27 end
28 }
29 end
30 self.inheritable_cattr_readers.uniq!
31 end
32
33 def cattr_inheritable_writer(*symbols)
34 symbols.each do |symbol|
35 self.inheritable_cattr_writers << symbol
36 self.module_eval %{
37 def self.#{symbol}=(value)
38 @#{symbol} = value
39 end
40 }
41 end
42 self.inheritable_cattr_writers.uniq!
43 end
44
45 def cattr_inheritable_accessor(*symbols)
46 cattr_inheritable_writer(*symbols)
47 cattr_inheritable_reader(*symbols)
48 end
49
50 def inherited_with_inheritable_class_attributes(klass)
51 inherited_without_inheritable_class_attributes(klass) if respond_to?(:inherited_without_inheritable_class_attributes)
52
53 readers = inheritable_cattr_readers.dup
54 writers = inheritable_cattr_writers.dup
55 inheritables = [:inheritable_cattr_readers, :inheritable_cattr_writers]
56
57 (readers + writers + inheritables).uniq.each do |attr|
58 var = "@#{attr}"
59 old_value = self.module_eval(var)
60 new_value = (old_value.dup rescue old_value)
61 klass.module_eval("#{var} = new_value")
62 end
63 end
64 end
65 en