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
|
# File 'lib/fallback.rb', line 20
def define_fallback(method, delegate_method, options)
delegate_method ||= method
define_attribute_methods if respond_to?(:define_attribute_methods)
define_method "#{method}_with_fallback" do
current = send("#{method}_without_fallback")
conditions = options.select{|k,v| [:if, :unless].include?(k)}
do_delegate = if conditions.empty?
current.to_s.strip.empty? else
conditions.map do |condition, value|
result = !!(value.respond_to?(:call) ? value.call(self) : send(value))
condition == :unless ? result : !result
end.all?
end
if do_delegate
delegate = (options[:to] ? send(options[:to]) : self )
delegate.send(delegate_method)
else
current
end
end
alias_method "#{method}_without_fallback", method
alias_method method, "#{method}_with_fallback"
end
|