/
shadows.rb
89 lines (74 loc) · 1.95 KB
/
shadows.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
module Shadows
def self.shadow_class(base, fallback = nil)
"#{ base.name }Shadow".constantize
rescue NameError => e
fallback or Class.new Shadows::Base do
helper = "#{ base.name.pluralize }Helper".constantize rescue nil
include helper if helper
end
end
@controllers = {}
def self.free_controller
@controllers.delete Thread.current
end
def self.controller
@controllers[ Thread.current ]
end
def self.controller=(ctrl)
@controllers[ Thread.current ] = ctrl
end
module Extension
def attach_shadows(opts = {})
extend Shadows::ClassMethods
include Shadows::InstanceMethods
shadow.options = opts.to_hash
end
end
class Filter
def self.filter(controller)
Shadows.controller = controller
yield
ensure
Shadows.free_controller
end
end
module ClassMethods
def self.extended(base)
base.instance_variable_set :@shadow, Shadows.shadow_class(base)
end
attr_reader :shadow
def inherited(base)
super
base.instance_variable_set :@shadow, Shadows.shadow_class(base, @shadow)
end
end
module InstanceMethods
def self.included(base)
base.class_eval do
alias_method :to_string_without_shadow, :to_s
alias_method :to_s, :to_string_with_shadow
end
end
def to_string_with_shadow(shape = nil, *args)
shadow = shadows[ Shadows.controller ]
shadow.to_s(shape, *args)
end
def shadows
@shadows ||= begin
shadow = self.class.shadow
Hash.new do |h, base|
template = shadow.new self, base
template.helpers.send :include, base.class.master_helper_module
h[base] = template
end
end
end
def render(shape = nil, *args)
shadow = shadows[ Shadows.controller ]
Shadows.controller.
instance_eval { render :text => shadow.to_s(shape), *args }
rescue
to_string_with_shadow shape, *args
end
end
end