-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconfig_prototype.rb
90 lines (75 loc) · 1.72 KB
/
config_prototype.rb
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class Config
class Entry
attr_accessor :klass, :name, :options
def initialize(klass, name)
@klass, @name = klass, name
@options = {}
end
def new
@klass.new
end
def add_option(name, default, description)
name = name.to_s
@options[name] = [default, description]
klass.class_eval(%{
attr_writer :#{name}
def #{name}
@#{name}.nil? ? Config.current.#{@name}.#{name} : @#{name}
end
})
end
def to_s
(["config.#{@name}.klass = #{@klass}"] + @options.keys.sort.map do |name|
"config.#{@name}.#{name} = #{@options[name][0]} # #{@options[name][1]}"
end).join("\n")
end
def method_missing(name, *args)
name = name.to_s
if name[-1,1] == '=' && option = @options[name[0..-1]]
option[0] = args[0]
elsif option = @options[name]
option[0]
else
super
end
end
end
def self.current
@current ||= new
end
attr_accessor :entries
def initialize
@entries = {}
end
def add_entry(klass, name)
name = name.to_s
entry = Entry.new(klass, name)
yield entry
@entries[name] = entry
end
def to_s
@entries.keys.sort.map do |name|
@entries[name].to_s
end.join("\n")
end
def method_missing(entry)
@entries[entry.to_s] || super
end
end
module Kernel
def config
Config.current
end
end
class Formatter
Config.current.add_entry(self, :formatter) do |entry|
entry.add_option(:use_inspect, true, "Call inspect on the object")
entry.add_option(:auto_indent, true, "Automatically indent code")
end
end
puts config
f = config.formatter.new
p f.use_inspect
f.use_inspect = false
p f.use_inspect
p f.auto_indent