blob: 1bd39a934963d300c83ee63e88093a9201be594f (
plain) (
blame)
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
|
require 'active_support/core_ext/object/singleton_class'
require 'active_support/core_ext/module/delegation'
class Class
# Declare a class-level attribute whose value is inheritable and
# overwritable by subclasses:
#
# class Base
# class_attribute :setting
# end
#
# class Subclass < Base
# end
#
# Base.setting = true
# Subclass.setting # => true
# Subclass.setting = false
# Subclass.setting # => false
# Base.setting # => true
#
# This matches normal Ruby method inheritance: think of writing an attribute
# on a subclass as overriding the reader method.
#
# For convenience, a query method is defined as well:
#
# Subclass.setting? # => false
def class_attribute(*attrs)
s = singleton_class
attrs.each do |attr|
s.send(:define_method, attr) { }
s.send(:define_method, "#{attr}?") { !!send(attr) }
s.send(:define_method, "#{attr}=") do |value|
singleton_class.send(:define_method, attr) { value }
end
end
end
end
|